var express = require('express');
var mysql = require('mysql');
var conf = require('./config/conf');
var common = require('./config/common');
var TelegramBot = require('node-telegram-bot-api');
var TronWeb = require('tronweb')
var cors = require('cors');
var fs = require('fs');
var moment = require('moment');
var request = require('request-promise');

var login = require('./api/login');
var chart = require('./api/chart');
var table = require('./api/table');
var result = require('./api/result');
const {inline_keyboard, chatid, jndqunid} = require('./config/conf');

const route = express.Router();
var app = express();
app.use(cors())
app.use(login);
app.use(chart);
app.use(table);
app.use(result);
var apitrc = `https://api.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` ////https://api.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t //https://nile.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj
var tzxz = "./img/pctzxz.jpg"
var ksxz = "./img/pcksxz.jpg"
var kjjg = "./img/pckjjg.jpg"
var fengpancishu = 0, iskey, iszaliu, a, b, c, daxiao, danshuang, jizhi, baozi, shunzi, duizi, value,
    date = new Date(), minutes,
    isfengpan = false, iskaijiang = true, resultArray = [], resultid = "1",
    resultCount = [
        {value: 0},
        {value: 0},
        {value: 0},
        {value: 0},
        {value: 0},
        {value: 0}
    ],
    resultdxds = {
        big: 0,
        small: 0,
        odd: 0,
        even: 0,
        baozi: 0,
        shunzi: 0,
        duizi: 0,
        jida: 0,
        jixiao: 0,
    },
    fengpantime = "",
    kaijiangtime = "",
    thisTime, nextTime, resultArr;
var HttpProvider = TronWeb.providers.HttpProvider;
var tronWeb = new TronWeb(new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), conf.trxPrivateKey);
//new TronWeb(new HttpProvider("https://api.trongrid.io")
//
//
// , new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), conf.trxPrivateKey);
//new TronWeb("https://api.nileex.io", "https://api.nileex.io", "https://api.nileex.io", conf.trxPrivateKey);
var contractaddress_usdt = "TGDVN1UC4jrAz1ZsNsgW2jV9xmVpiADn1o"; //TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t //TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj
var server = app.listen(conf.port, function () {
    /*监听充值订单*/
    setInterval(function () {
        date = new Date();
        checkbetguoqi()

        if (resultid == 1) {
            request(`https://www.pc28yx.com/get_data`).then(body => {
                let jsonBody = JSON.parse(body)
                console.log('jsonBody.type=======',jsonBody.type)
                console.log('jsonBody.type=======',jsonBody)
                if (jsonBody.type === 'jnd28') {
                    iskaijiang = true
                    resultArr = jsonBody.issue
                    console.log('======开始查接口，第一个=======', resultArr[0])
                    fengpantime = moment(parseInt(resultArr[0].next + '000') + (1000 * 60 * 3) + (1000 * 20)).valueOf()
                    console.log('======下一个时间=======', resultArr[0])

                    resultid = parseInt(resultArr[0].qishu) + 1
                    setResultID()
                }
            });
        }

        let momentTime = moment(Math.round(date))
        let difference = moment(fengpantime - momentTime.valueOf())


        if (iskaijiang && difference.get('seconds') == 30 && difference.get('minutes') == 0) {
            fengpantixing()
        }

        if (difference.get('seconds') == 0 && difference.get('minutes') == 0) {
            console.log('开奖============')

            console.log ('beforArr', resultArr[0])
            request(`https://www.pc28yx.com/get_data`).then(body => {
                let jsonBody = JSON.parse(body)
                if (jsonBody.type === 'jnd28') {
                    console.log('resultArr[0].qishu',resultArr[0].qishu)
                    console.log('jsonBody.issue[0].qishu====',jsonBody.issue[0].qishu)
                    if (jsonBody.issue[0].qishu == resultArr[0].qishu) {
                        iskaijiang = false
                        return;
                    }
                    iskaijiang = true
                    resultArr = jsonBody.issue

                    console.log('afterArr', resultArr[0])
                    fengpantime = moment(parseInt(resultArr[0].next + '000') + (1000 * 60 * 3) + (1000 * 20)).valueOf()
                    // nextTime = parseInt(resultArr[0].next + '000') + (1000 * 60 * 3) + (1000 * 30)
                    resultid = parseInt(resultArr[0].qishu) + 1
                    getAllBet()
                    setTimeout(function (params) {
                        console.log('=================开始下注=============')
                        setResultID()
                    }, 3000)
                }
            });
        }

        // 当前时间距离封盘时间3分钟30秒时，开始下注
        /*            if (fengpantime && momentTime && difference.get('seconds') == 25 && difference.get('minutes') == 3) {

                    }*/


        /*console.log('nextTime - momentTime====',
            new Date(fengpantime).toLocaleString('chinese', {hour12: false})
            , new Date(momentTime.valueOf()).toLocaleString('chinese', {hour12: false}));
*/

    }, 1000)


})


var bot = new TelegramBot(conf.token, {polling: true});
var allkeyword = ["输赢", "账单", "查询", "游戏", "/start", "我要充值", "🏧佣金提现", "游戏规则", "开始游戏", "🏠代理中心", "最近投注", "账单记录", "个人中心", "实时佣金排名", "取消", "撤回", "历史", "上分", "下分", "大", "小", "单", "双", "豹子", "对子", "顺子", "押", "T", "哈", "1", "2", "3", "反水", "余额"]

/*监听新的文字消息*/
bot.on("dice", (msg) => {
    console.log('msg=====', msg)

    if (!msg.from.is_bot) {
        bot.deleteMessage(msg.chat.id, msg.message_id)
    }
    // fashazi(msg)
})

bot.on('text', (msg) => {
    console.log('msg==========', msg)
    if (msg.text == "大" || msg.text == "小" || msg.text == "单" || msg.text == "双" || msg.text == "豹子" || msg.text == "对子" || msg.text == "顺子" || msg.text == "押" || msg.text == "哈") {
        return;
    }
    if (msg.text.search(`\\+`) != -1 && checkarray(msg.from.id, conf.adminid) && msg.reply_to_message) {
        shangfenadmin(msg.text, msg.reply_to_message.from.id, (msg.reply_to_message.from.first_name ? msg.reply_to_message.from.first_name : "") + (msg.reply_to_message.from.last_name ? msg.reply_to_message.from.last_name : ""), msg.message_id, msg.reply_to_message.from.username, msg.from.username, msg.reply_to_message.message_id, msg.chat.id)
    } else if (msg.text.search(`\\-`) != -1 && checkarray(msg.from.id, conf.adminid) && msg.reply_to_message) {
        xiafenadmin(msg.text, msg.reply_to_message.from.id, (msg.reply_to_message.from.first_name ? msg.reply_to_message.from.first_name : "") + (msg.reply_to_message.from.last_name ? msg.reply_to_message.from.last_name : ""), msg.message_id, msg.reply_to_message.from.username, msg.from.username, msg.chat.id)
    } else if (msg.text == "签到") {
        qiandao(msg.text, msg.from.id, (msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""), msg.message_id, msg.from.username, msg.chat.id)
    } else if (msg.text == "cz" && checkarray(msg.from.id, conf.adminid)) {
        isfengpan = false;
    } else if (msg.text == "游戏") {
        allgame(msg)
    } else if (msg.text.search("yj") == 0 && checkarray(msg.from.id, conf.adminid)) {
        yongjintixian(msg.text, msg.reply_to_message.from.id, (msg.reply_to_message.from.first_name ? msg.reply_to_message.from.first_name : "") + (msg.reply_to_message.from.last_name ? msg.reply_to_message.from.last_name : ""), msg.message_id, msg.reply_to_message.from.username, msg.from.username, msg.chat.id)
    } else if (msg.chat.id == conf.houtaiqunid) {
        if (msg.text.search("\\+") != -1 || msg.text.search("\\-") != -1) {
            topupgroup(msg)
        } else if (msg.text.search("qh") == 0) {
            checkqihao(msg)
        } else if (msg.text.search("qx") == 0) {
            backqihao(msg)
        } else if (msg.text.search("pc20qx") == 0) {
            pc20backqihao(msg)
        } else if (msg.text.search("pc28qx") == 0) {
            pc28backqihao(msg)
        }
    }


    if (msg.forward_date == undefined && msg.text) {
        if (msg.chat.id == conf.chatid || msg.chat.id == conf.sxfqunid || msg.chat.type == 'private') {
            var msgtxt = msg.text;
            iskey = false;
            for (let index = 0; index < allkeyword.length; index++) {
                if (msgtxt.search(allkeyword[index]) != -1 || parseInt(msgtxt) % 1 == 0 || tronWeb.isAddress(msgtxt)) {
                    iskey = true;
                }
            }
            console.log('iskey=====', iskey)
            if (iskey) {
                console.log('进来查库了');
                conf.pool.getConnection(function (err, connection) {
                    console.log('err====', err)
                    if (err) return err;
                    console.log(`SELECT *
                                 FROM users
                                 where telegramid = "${msg.from.id}"`)
                    connection.query(`SELECT *
                                      FROM users
                                      where telegramid = "${msg.from.id}"`, (error, result) => {
                        console.log('result==', result)

                        if (result.length == 0) {
                            var inviter_telegramid = msg.text.split(" ")[1];
                            if (!inviter_telegramid || parseInt(inviter_telegramid) % 1 != 0) {
                                inviter_telegramid = "无邀请人"
                            }
                            connection.query(`Insert into users (name, nickname, telegramid, register_time, inviter_telegramid)
                                              values ("${(msg.from.username ? msg.from.username : "")}",
                                                      "${utf16toEntities((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))}",
                                                      "${msg.from.id}", now(),
                                                      "${inviter_telegramid}");`, (error, result) => {
                                connection.destroy();
                                if (error) return error;
                                if (msg.chat.id == conf.chatid) {
                                    main(msg);
                                } else if (msg.chat.id == conf.sxfqunid) {
                                    sxf(msg);
                                } else if (msg.chat.type == 'private') {
                                    privatemain(msg)
                                }
                            });
                        } else {
                            console.log('更新用户=====================')
                            connection.query(`update users
                                              set name          = "${(msg.from.username ? msg.from.username : "")}",
                                                  nickname      = "${utf16toEntities((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))}",
                                                  lastchat_time = now()
                                              where telegramid = "${msg.from.id}";`, (error, result) => {
                                connection.destroy();
                                if (error) return error;
                                if (msg.chat.id == conf.chatid) {
                                    console.log("=====进入主函数")
                                    main(msg);
                                } else if (msg.chat.id == conf.sxfqunid) {
                                    console.log("=====进入上下分主函数")
                                    sxf(msg);
                                } else if (msg.chat.type == 'private') {
                                    console.log("=====进入私有群主函数")
                                    privatemain(msg)
                                }
                            });
                        }
                    })
                })
            }
        }
    }
});

/*监听错误*/
bot.on('error', (error) => {
    console.log("监听到普通错误：" + date + error);
});
bot.on('polling_error', (error) => {
    console.log("监听到轮循错误：" + date + error);
});
bot.on('webhook_error', (error) => {
    console.log("监听到webhook错误：" + date + error);
});

function pc28backqihao(msg) {
    var qihao = msg.text.split("pc28qx")[1];
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and resultid = "${qihao}";`, (error, result) => {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users
                            set balance = balance ${(result[index].result - result[index].amount < 0 ? "+" + (result[index].amount - result[index].amountreturn) : "-" + (result[index].result - result[index].amount - result[index].amountreturn))}
                            where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`, {
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}
            delete
            from pc_bet
            where type = '${conf.type}'
              and resultid = "${qihao}";`, (error, result) => {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}

function checkbetguoqi() {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and result is null
                            and time
                              < "${moment(Math.round(date) - 300000).format("YYYY-MM-DD HH:mm:ss")}"
                            and one is null;`, (error, result) => {
            if (error) throw error;
            if (result[0]) {
                bot.sendMessage(conf.chatid, `<b>投注已经过期,本期下注金额不退</b>\n\n用户：<a href="http://t.me/${result[0].name}">${utf16toEntities(result[0].firstname)}</a> \n下注：${result[0].guess}-${result[0].amount} `, {
                    parse_mode: "HTML",
                    disable_web_page_preview: true
                })
                //退回的
                /*connection.query(`update pc_bet set result = -1 where type = ${conf.type} and id = "${result[0].id}";update users set balance = balance + ${result[0].amount} where telegramid = "${result[0].telegramid}";`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                });*/
                connection.query(`update pc_bet
                                  set result = -1
                                  where type = ${conf.type}
                                    and id = "${result[0].id}";`, (error, result) => {
                    connection.destroy();
                    if (error) return error;
                });
            } else {
                connection.destroy();
            }

        });

    })
}

function pc20backqihao(msg) {
    var qihao = msg.text.split("pc20qx")[1];
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM jndbet
                          where resultid = "${qihao}";`, (error, result) => {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users
                            set balance = balance ${(result[index].result - result[index].amount < 0 ? "+" + (result[index].amount - result[index].amountreturn) : "-" + (result[index].result - result[index].amount - result[index].amountreturn))}
                            where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`, {
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}
            delete
            from jndbet
            where resultid = "${qihao}";`, (error, result) => {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}

function backqihao(msg) {
    var qihao = msg.text.split("qx")[1];
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and resultid = "${qihao}";`, (error, result) => {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users
                            set balance = balance ${(result[index].result - result[index].amount < 0 ? "+" + (result[index].amount - result[index].amountreturn) : "-" + (result[index].result - result[index].amount - result[index].amountreturn))}
                            where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`, {
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}
            delete
            FROM pc_bet
            where type = '${conf.type}'
              and resultid = "${qihao}";`, (error, result) => {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}


function fashazi() {
    conf.pool.getConnection(function (err, connection) {
        console.log('扔色子====', err)
        let resultid = resultArr[0].qishu
        console.log('resultid====', resultid)
        if (err) return err;

        connection.query(`SELECT *
                          FROM pc_bet
                          WHERE type = '${conf.type}'
                            and resultid = "${resultid}"
                            and result is null;
        SELECT *
        FROM pc_result
        where type = '${conf.type}'
          and id = "${resultid}"`, (error, result) => {
            console.log('扔色子查询=====', error)
            console.log('扔色子查询=====', result)
            connection.destroy();

            if (error) return error;
            // console.log('result[0]====', result)

            console.log('abc=====', resultArr[0].num1)
            console.log('abc=====', resultArr[0].num2)
            console.log('abc=====', resultArr[0].num3)
            if (result[1][0]) {
                console.log('resultArr====', resultArr[0])
                conf.pool.getConnection(function (err, connection) {
                    console.log(err)
                    console.log('resultArr====', resultArr[0])
                    if (err) return err;
                    let updateBet = ``
                    if (resultArr[0]) {
                        a = resultArr[0].num1
                        b = resultArr[0].num2
                        c = resultArr[0].num3
                        // nextTime = resultArr[0].next
                        // resultid = parseInt(resultArr[0].qishu) + 1
                        updateBet = `update pc_bet
                                     set one   = "${resultArr[0].num1}",
                                         two   = "${resultArr[0].num2}",
                                         three = "${resultArr[0].num3}"
                                     where type = ${conf.type}
                                       and resultid = "${resultid}";`
                    }

                    connection.query(`${updateBet}
                    update pc_result
                    set one   = "${resultArr[0].num1}",
                        two   = "${resultArr[0].num2}",
                        three = "${resultArr[0].num3}"
                    where type = ${conf.type}
                      and id = ${resultid};`, (error, result) => {
                        console.log('oneErr=============', error)
                        connection.destroy();
                        setResult()
                    });

                })


                /*else if (b !== 0) {
                   conf.pool.getConnection(function (err, connection) {
                       console.log(err)
                       if (err) return err;
                       let updateBet = ``
                       if (result[0][0]) {
                           updateBet = `update pc_bet
                                        set two = "${b}"
                                        where type = ${conf.type} and resultid = "${resultid}";`
                       }
                       connection.query(` ${updateBet}
                       update pc_result
                       set two = ${msg.dice.value}
                       where id = ${resultid};`, (error, result) => {
                           console.log('twoerror===', error)
                           connection.destroy();
                       });

                   })
               } else if (c !== 0) {
                   conf.pool.getConnection(function (err, connection) {
                       if (err) return err;
                       let updateBet = ``
                       if (result[0][0]) {
                           updateBet = `update pc_bet
                                        set three = "${c}"
                                        where resultid = "${resultid}";`
                       }
                       connection.query(`${updateBet}
                       update pc_result
                       set three = ${msg.dice.value}
                       where id = ${resultid};`, (error, result) => {
                           console.log('threeerror===', error)
                           connection.destroy();
                           setResult(msg);
                       });

                   })
               }*/
            }
        });

    })
}

function checkqihao(msg) {
    var qihao = msg.text.split("qh")[1];
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and resultid = ${qihao};`, (error, result) => {
            connection.destroy();
            if (error) return error;
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;
            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注</b>\n\n${allbet}`, {
                parse_mode: 'HTML'
            })
        });

    })
}

function topupgroup(msg) {
    if (msg.text.search("\\+") != -1) {
        var czjine = "+" + msg.text.split("+")[1];
        var telegramid = msg.text.split("+")[0];
    }

    if (msg.text.search("\\-") != -1) {
        var czjine = "-" + msg.text.split("-")[1];
        var telegramid = msg.text.split("-")[0];
    }
    if (telegramid % 1 != 0 || telegramid.length < 9) {
        return
    }
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;

        connection.query(`SELECT *
                          FROM users
                          where telegramid = ${telegramid};`, (error, result) => {
            if (error) return error;
            connection.query(`update users
                              set balance = balance ${czjine}
                              where telegramid = "${telegramid}";`, (error, res) => {
                connection.destroy();
                if (error) return error;

                if (result.length > 0) {
                    bot.sendMessage(conf.houtaiqunid, `用户: ${(result[0].nickname ? result[0].nickname : "")}\nID: <code>${result[0].telegramid}</code>\n余额:${result[0].balance}\n充值金额：${czjine}`, {
                        parse_mode: 'HTML'
                    })
                } else {
                    bot.sendMessage(msg.chat.id, `用户未注册`, {
                        parse_mode: 'HTML'
                    })
                }


            });
        });

    })
}

/*监听内联键盘*/
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
    if (callbackQuery.data.search("fanye") == 0) {
        fanyecktd(callbackQuery)
    }
    if (!isfengpan) {
        switch (callbackQuery.data) {
            case "6":
                getBalance(callbackQuery.from.id, callbackQuery.from.username, callbackQuery.id);
                break;
            case "7":
                getMyBet(callbackQuery.from.id, callbackQuery.from.username, callbackQuery.id);
                break;
            case "8":
                getTodayBill(callbackQuery.from.id, (callbackQuery.from.first_name ? callbackQuery.from.first_name : "") + (callbackQuery.from.last_name ? callbackQuery.from.last_name : ""), callbackQuery.id);
                break;
            case "9":
                getReturnWater(callbackQuery.from.id, callbackQuery.from.username, callbackQuery.id);
                break;
            case "qxorder":
                qxorder(callbackQuery)
                break;
            case "lstj":
                tongji(callbackQuery.from.id, callbackQuery.from.username, callbackQuery.id);
                break;
            case "qbtx":
                quanbutixian(callbackQuery.from.id, callbackQuery.message.chat.id, callbackQuery.message.message_id, callbackQuery.id)
                break;
            case "cktd":
                cktd(callbackQuery)
                break;
            case "backdaili":
                backdaili(callbackQuery)
                break;
            default:
                break;
        }
    }
});

function allgame(msg) {
    bot.sendMessage(msg.chat.id, `点击下方按钮进入游戏群`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
        reply_markup: {
            inline_keyboard: conf.game_line_keyboard
        }
    })
}


function start(msg) {
    bot.sendMessage(msg.chat.id, `<b>📣${((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))}，感谢您的关注!</b>\n\n\n<a href="${conf.youxigrouplink}">手摇快三游戏</a>开奖采用<a href="https://core.telegram.org/api/dice">Telegram官方骰子</a>\n以保证游戏过程的绝对随机和绝对公平 ！`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
        reply_markup: {
            inline_keyboard: conf.start_line_keyboard
        }
    })
        .then(res => {
            bot.sendMessage(msg.chat.id, `<b>✅已开启键盘</b>`, {
                parse_mode: "HTML",
                reply_markup: {
                    keyboard: conf.keyboard,
                    resize_keyboard: true
                }
            })
        })
}


function fuli(msg) {
    bot.sendMessage(msg.chat.id, `（福利活动多多）
下注看好规则
切勿超额下注，否则不负责任
认准财务ID
充值直接进群。https://t.me/+321

唯一收款地址:
TWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd

每日首次充值以上100rmb送6%🎉

每次充值活动只能选一个 ❗️❗️❗️

后续充值笔笔送4%🎉🎉🎉

（送彩金上限388RMB）💰
发现刷彩金的直接扣除拉黑
（骰子每天仅限三次）
下注流水实时反1%🎉
当天负盈利反5%）
负盈利每日12:00自动反5%
负盈利回水须满足1倍流水才可提现！

⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️
抽奖模式每次单笔充值300RMB以上
认准财务ID: @Xiy99999
即可获得一次抽奖机会
🎲🎲摇骰子活动🎲🎲🔥
即日起凡是在夕阳集团充值达到要求的玩家，上分成功后均可参加摇骰子活动:充值300以上即可抽奖
🎁骰子🎲出现一个6，奖励38RMB
🎁骰子🎲出现两个6，奖励66 RMB
🎁骰子🎲出现三个6，奖励666 RMB
充值2000以上
🎁骰子🎲出现一个6，奖励108RMB
🎁骰子🎲出现两个6，奖励333 RMB
🎁骰子🎲出现三个6，奖励2222 RMB

(摇骰子要根据客服的指示摇！！)
快三每日签到福利🎁🎁🎁
每日充值500以上
凌晨12点-1:00开始签到
过时无效，重新归零
第一天  6               第二天12
第三天18               第四天28
第五天38               第六天48
第七天58   
领取要求如下当天投注满20把(每把10以上满足要求即可联系客服申请，领取的福利1倍流水即可下分）

爆庄奖励 🎁🎁🎁
1w奖励188.  5w奖励588.   10w奖励888.   30w奖励1888  50w奖励2888
100w奖励18888
输+赢活动 🎁🎁🎁

当天输赢1000以上参加活动
发三个骰子
一个6奖励6
二个6奖励38
三个6奖励88

特别提醒，晚上12点过后 一律按客服提示掷色子
所有奖励1倍流水下分。

每天12:00点福利 🧧🧧🧧
充值满3000以上可参与并有效
会在上分内部群聊里发1000红包
领取到奖励.1倍流水可下分


（每人每天反限三次机会）

（充值必须打满1倍流水才可下分）
（防止洗钱 多次，上多少下多少⚠️）
同一个人，转帐，每个帐户名不一样
加上，上多少下多少，直接扣分拉黑
判为洗钱，⚠️⚠️⚠️别来找事`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
    });
}


function guizehuodong(msg) {
    bot.sendMessage(msg.chat.id, `------------------------------------
加拿大2.8  pc28
下注格式为：单1000 大单2000
押单数格式为：数字+押+金额：例10押100
—— —— —— —— —— —— —— ——
🏆玩法限额/赔率：
♦️大小单双（10-10W）
♦️组合（10-10W）
♦️数字（10-2000）
🔹对子（10-300）3倍
🔹顺子（10-300）11倍
🔹豹子（10-100）60倍
🔹极值（10-300）15倍
🔥大小单双 2.8倍🔸小单大双6.0倍🔸大单小双 6.0倍
⚠️遇13/14 、对子、顺子、豹子 回本
（注：开出890/190等三个数字均为顺子）
—— —— —— —— —— —— —— ——
0/27=500倍   💵  1/26=120倍
2/25=98倍     💵  3/24=58倍
4/23=48倍     💵  5/22=32倍
6/21=25倍     💵  7/20=20倍
8/19=17倍     💵  9/18=15倍
10/17=14倍   💵  11/16=13倍
12/15=12倍   💵  13/14=10倍
—— —— —— —— —— —— —— ——
游戏规则
因为接口问题和卡BUG问题（退回本金重新下注）

🔥游戏规则：
⚠️本群下注无任何限制！

🈲🈲主动私信上分的都是骗子,以机器人录入结算为准！
凡是游戏程序出错期间,利用bug进行套利的，我方有权扣除盈利部分，只返还本金

以上活动最终解释权归【鑫达聚】所有！
🔥总注10万封顶❗️ 
🔥【反水】立即派送❗️
🔰🔰🔰🔰🔰🔰🔰🔰🔰`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
    });
}

function kaishiyouxi(msg) {
    bot.sendMessage(msg.chat.id, `<a href="${conf.youxigrouplink}">加入群组，开始游戏！</a>`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
    });
}

function zuijintouzhu(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = '${msg.from.id}'
                            and result >= 0
                          order by id desc LIMIT 50;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            console.log(result);
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (result[index].result == 0) {
                    result_money = `❌`
                } else {
                    result_money = `✅`
                }
                myBet = `${myBet}${result_money} <code>${result[index].resultid}</code> - ${result[index].guess} - <code>${result[index].amount}</code>\n`;
            }
            bot.sendMessage(msg.chat.id, `<b>最近50条投注记录</b>\n\n${myBet}`, {
                parse_mode: "HTML"
            })
        });
    });
}

function zhangdanjilu(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        console.log(err)
        connection.query(`SELECT *
                          FROM pay
                          where telegramid = '${msg.from.id}'
                            and state = 1
                            and way = "群内管理上分"
                          order by id desc LIMIT 10;
        SELECT *
        FROM withdrawal
        where telegramid = '${msg.from.id}'
          and state = 1
        order by id desc LIMIT 10;
        SELECT *
        FROM jiangli
        where telegramid = '${msg.from.id}'
        order by id desc LIMIT 10;`, (error, result) => {
            console.log(error)
            if (error) return error;
            connection.destroy();
            var chongzhi = "";
            var tixian = "";
            var jiangli = "";
            for (let index = 0; index < result[0].length; index++) {
                chongzhi = `${chongzhi}【${result[0][index].applytime.split("2023-")[1].substring(result[0][index].applytime.split("2023-")[1].length - 3, result[0][index].applytime.split("2023-")[1])}】${result[0][index].amount}${conf.coin}\n`;
            }
            for (let index = 0; index < result[1].length; index++) {
                tixian = `${tixian}【${result[1][index].applytime.split("2023-")[1].substring(result[1][index].applytime.split("2023-")[1].length - 3, result[1][index].applytime.split("2023-")[1])}】${result[1][index].amount}${conf.coin}\n`;
            }

            for (let index = 0; index < result[2].length; index++) {
                jiangli = `${jiangli}【${result[2][index].time.split("2023-")[1].substring(result[2][index].time.split("2023-")[1].length - 3, result[2][index].time.split("2023-")[1])}】${result[2][index].type} ${result[2][index].amount}${conf.coin}\n`;
            }
            bot.sendMessage(msg.chat.id, `<b>最近20条账单</b>\n\n充值:\n<code>${chongzhi}</code>\n提现:\n<code>${tixian}</code>`, {
                parse_mode: "HTML"
            })
        });
    });
}

function cktd(callbackQuery) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where inviter_telegramid = '${callbackQuery.from.id}' limit 20;
        SELECT count(*)
        FROM users
        where inviter_telegramid = '${callbackQuery.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var list = ""
            for (let index = 0; index < result[0].length; index++) {
                if (result[0][index].name == "") {
                    list += `${index + 1}.${(result[0][index].nickname == null ? "未知用户" : result[0][index].nickname)}\n`;
                } else {
                    list += `${index + 1}.<a href="https://t.me/${result[0][index].name}">${(result[0][index].nickname == null ? "未知用户" : result[0][index].nickname)}</a>\n`;
                }
            }
            if (list == "") {
                list = '您还没有团队成员，请再接再厉哦！'
            }
            var allbuttonarray = []
            if (result[1][0]["count(*)"] > 20) {
                allbuttonarray = [[{text: "➡️下一页", callback_data: "fanye_2"}]]
            }
            allbuttonarray.push([{text: "返回", callback_data: "backdaili"}])
            bot.editMessageText(`${list}`, {
                chat_id: callbackQuery.message.chat.id,
                message_id: callbackQuery.message.message_id,
                parse_mode: "HTML",
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: allbuttonarray
                }

            })
        });
    });
}

function fanyecktd(callbackQuery) {
    var yeshu = parseInt(callbackQuery.data.split("_")[1])
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where inviter_telegramid = '${callbackQuery.from.id}' limit ${(yeshu - 1) * 20}
                              , 20;
        SELECT count(*)
        FROM users
        where inviter_telegramid = '${callbackQuery.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var list = ""
            for (let index = 0; index < result[0].length; index++) {
                if (result[0][index].name == "") {
                    list += `${index + 1}.${(result[0][index].nickname == null ? "未知用户" : result[0][index].nickname)}\n`;
                } else {
                    list += `${index + 1}.<a href="https://t.me/${result[0][index].name}">${(result[0][index].nickname == null ? "未知用户" : result[0][index].nickname)}</a>\n`;
                }
            }
            if (list == "") {
                list = '您还没有团队成员，请再接再厉哦！'
            }
            var allbuttonarray = []
            var allbuttonarray = [[{text: "⬅️上一页", callback_data: `fanye_${yeshu - 1}`}]]
            if (yeshu == 1) {
                allbuttonarray = [[{text: "➡️下一页", callback_data: `fanye_${yeshu + 1}`}]]
            } else if (result[0].length == 20) {
                allbuttonarray = [[{text: "⬅️上一页", callback_data: `fanye_${yeshu - 1}`}, {
                    text: "➡️下一页",
                    callback_data: `fanye_${yeshu + 1}`
                }]]
            }
            allbuttonarray.push([{text: "返回", callback_data: "backdaili"}])
            bot.editMessageText(`${list}`, {
                chat_id: callbackQuery.message.chat.id,
                message_id: callbackQuery.message.message_id,
                parse_mode: "HTML",
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: allbuttonarray
                }

            })
        });
    });
}

function usercenter(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = '${msg.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>📇个人中心</b>\n\n用户账号：<code>${result[0].telegramid}</code>\n用户昵称：<code>${((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))}</code>\n游戏余额：<code>${result[0].balance}元</code>\n\n累计流水：<code>${result[0].zongliushui}</code>`, {
                parse_mode: "HTML"
            })
        });
    });
}

function dailizhongxin(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*)
                          FROM users
                          where inviter_telegramid = '${msg.from.id}';
        SELECT count(*)
        FROM users
        where inviter_telegramid = '${msg.from.id}'
          and lastchat_time like '${moment().format("YYYY-MM")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}'
          and time like '${moment().format("YYYY-MM-DD")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}'
          and time like '${moment().format("YYYY-MM")}%';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>邀请好友前来游戏,永久享受${conf.yongjin * 100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${msg.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)'] ? result[0][0]['count(*)'] : 0)}人（活跃：${(result[1][0]['count(*)'] ? result[1][0]['count(*)'] : 0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)'] ? result[2][0]['sum(amount)'] * conf.yongjin : 0)}（当日：${(result[3][0]['sum(amount)'] ? result[3][0]['sum(amount)'] * conf.yongjin : 0)}    当月：${(result[4][0]['sum(amount)'] ? result[4][0]['sum(amount)'] * conf.yongjin : 0)}）`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: [
                        [{text: "查看团队", callback_data: "cktd"}]
                    ]
                }
            });
        });
    });

}

function dailizhongxinstart(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*)
                          FROM users
                          where inviter_telegramid = '${msg.from.id}';
        SELECT count(*)
        FROM users
        where inviter_telegramid = '${msg.from.id}'
          and lastchat_time like '${moment().format("YYYY-MM")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}'
          and time like '${moment().format("YYYY-MM-DD")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${msg.from.id}'
          and time like '${moment().format("YYYY-MM")}%';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>邀请好友前来游戏,永久享受${conf.yongjin * 100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${msg.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)'] ? result[0][0]['count(*)'] : 0)}人（活跃：${(result[1][0]['count(*)'] ? result[1][0]['count(*)'] : 0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)'] ? result[2][0]['sum(amount)'] * conf.yongjin : 0)}（当日：${(result[3][0]['sum(amount)'] ? result[3][0]['sum(amount)'] * conf.yongjin : 0)}    当月：${(result[4][0]['sum(amount)'] ? result[4][0]['sum(amount)'] * conf.yongjin : 0)}）`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: [
                        [{text: "查看团队", callback_data: "cktd"}]
                    ]
                }
            })
                .then(res => {
                    bot.sendMessage(msg.chat.id, `<b>✅已开启键盘</b>`, {
                        parse_mode: "HTML",
                        reply_markup: {
                            keyboard: conf.keyboard
                        }
                    })
                })
        });
    });

}

function backdaili(callbackQuery) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*)
                          FROM users
                          where inviter_telegramid = '${callbackQuery.from.id}';
        SELECT count(*)
        FROM users
        where inviter_telegramid = '${callbackQuery.from.id}'
          and lastchat_time like '${moment().format("YYYY-MM")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${callbackQuery.from.id}';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${callbackQuery.from.id}'
          and time like '${moment().format("YYYY-MM-DD")}%';
        SELECT sum(amount)
        FROM pc_bet
        where type = '${conf.type}'
          and inviter_telegramid = '${callbackQuery.from.id}'
          and time like '${moment().format("YYYY-MM")}%';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.editMessageText(`<b>邀请好友前来游戏,永久享受${conf.yongjin * 100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${callbackQuery.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)'] ? result[0][0]['count(*)'] : 0)}人（活跃：${(result[1][0]['count(*)'] ? result[1][0]['count(*)'] : 0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)'] ? result[2][0]['sum(amount)'] * conf.yongjin : 0)}（当日：${(result[3][0]['sum(amount)'] ? result[3][0]['sum(amount)'] * conf.yongjin : 0)}    当月：${(result[4][0]['sum(amount)'] ? result[4][0]['sum(amount)'] * conf.yongjin : 0)}）`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                chat_id: callbackQuery.message.chat.id,
                message_id: callbackQuery.message.message_id,
                reply_markup: {
                    inline_keyboard: [
                        [{text: "查看团队", callback_data: "cktd"}]
                    ]
                }
            });
        });
    });

}

function address(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`update users
                          set trx_address = "${msg.text}"
                          where telegramid = "${msg.from.id}";`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `✅设置成功\n\n提佣地址：<code>${msg.text}</code>`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                reply_to_message_id: msg.message_id,
            });
        });
    })

}

function chongzhi(msg) {
    bot.sendMessage(msg.chat.id, `<a href="https://t.me/+DYsIFImeDB8xNTQ1">立即加入上下分群</a>`, {
        parse_mode: 'HTML',
        disable_web_page_preview: true,
    });
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`update users
                          set privatetype = "cz"
                          where telegramid = '${msg.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>▶️请输入您要充值的正整数金额，如：5000\n🔺请注意，充值最小金额为30</b>`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
            });
        });
    });

}

function tixian(msg) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`select *
                          from users
                          where telegramid = '${msg.from.id}';
        update users
        set privatetype = "tx"
        where telegramid = '${msg.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>点击下方按钮，立即提现</b>\n\n佣金余额：<code>${result[0][0].yongjinbalance}元</code>`, {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: conf.yongjintixian_line_keyboard
                }
            });
        });
    });
}

function shuzi(msg) {
    return
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = '${msg.from.id}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            if (result[0].privatetype == "cz") {
                if (conf.czMin > parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id, `请输入不小于${conf.czMin}的正整数金额！`)
                    return
                }
                conf.pool.getConnection(function (err, connection) {
                    if (err) return err;
                    connection.query(`SELECT *
                                      FROM pay
                                      where telegramid = '${msg.from.id}'
                                        and state = 0;`, (error, result) => {
                        if (error) return error;
                        connection.destroy();
                        if (result[0]) {
                            bot.sendMessage(msg.from.id, `<b>您还有未完成的充值订单！</b>\n\n此订单10分钟内有效，过期后请重新生成订单。\n➖➖➖➖➖➖➖➖➖➖\n转账地址: <code>${conf.czaddress}</code> (TRC-20网络)\n转账金额: <code>${result[0].amount}</code> USDT\n➖➖➖➖➖➖➖➖➖➖\n请使用绑定的 请等待1分钟左右查询，自动到账。`, {
                                parse_mode: 'HTML',
                                reply_markup: {
                                    inline_keyboard: [[{text: "❎ 取消订单", callback_data: "qxorder"}]]
                                },
                            })
                        } else {
                            var czjine = (parseInt(msg.text) + (Math.random() * (100 - 1) + 1) / 1000).toFixed(3)
                            bot.sendMessage(msg.from.id, `<b>此订单10分钟内有效，过期后请重新生成订单。</b>\n➖➖➖➖➖➖➖➖➖➖\n转账地址: <code>${conf.czaddress}</code> (TRC-20网络)\n转账金额: <code>${czjine}</code> USDT\n➖➖➖➖➖➖➖➖➖➖\n请使用绑定的 请等待1分钟左右查询，自动到账。`, {
                                parse_mode: 'HTML',
                                reply_markup: {
                                    inline_keyboard: [[{text: "❎ 取消订单", callback_data: "qxorder"}]]
                                },
                            }).then(res => {
                                conf.pool.getConnection(function (err, connection) {
                                    if (err) return err;
                                    connection.query(`Insert into pay (name, username, telegramid, amount, state, way,
                                                                       applytime, applytimestamp, replyMessageid)
                                                      values ("${utf16toEntities((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))}",
                                                              "${msg.from.username}", "${msg.from.id}", ${czjine}, 0,
                                                              "USDT自动充值", now(), unix_timestamp(),
                                                              ${res.message_id});`, (error, result) => {
                                        connection.destroy();
                                        if (error) return error;

                                    });
                                })
                            })

                        }
                    });
                });


            } else if (result[0].privatetype == "tx") {
                if (conf.txMin > parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id, `<b>❌请输入不小于${conf.txMin}的正整数金额！</b>`, {
                        parse_mode: "HTML"
                    })
                    return
                } else if (result[0].yongjinbalance < parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id, `<b>❌佣金余额不足，无法发起提现！</b>`, {
                        parse_mode: "HTML"
                    })
                    return
                } else if (result[0].trx_address == "暂未绑定") {
                    bot.sendMessage(msg.chat.id, `<b>❌暂未设置提现地址，请发送TRC20地址进行绑定！</b>`, {
                        parse_mode: "HTML"
                    })
                    return
                } else {
                    var trx_address = result[0].trx_address;
                    var txamount = (parseFloat(msg.text) * (1 - conf.txfee) / conf.utormb).toFixed(2)
                    transferUSDT(result[0].trx_address, txamount)
                        .then(res => {
                            conf.pool.getConnection(function (err, connection) {
                                if (err) return err;
                                connection.query(`Insert into withdrawal (name, telegramid, amount, state, way,
                                                                          applytime, changetime, replyMessageid, hashid,
                                                                          trx_address)
                                                  values ("${msg.from.username}", "${msg.from.id}", ${msg.text}, 1,
                                                          "USDT", now(), now(), ${msg.message_id}, "${hashid}",
                                                          "${trx_address}");
                                update users
                                set balance = balance - ${msg.text}
                                where telegramid = "${msg.from.id}";`, (error, result) => {
                                    connection.destroy();
                                    if (error) return error;
                                    bot.sendMessage(msg.from.id, `<b>✅${txamount}USDT提现成功，请注意查收~</b>`, {
                                        parse_mode: 'HTML',
                                        reply_markup: {
                                            inline_keyboard: [
                                                [{
                                                    text: "查看详情",
                                                    url: `https://tronscan.org/#/transaction/${hashid}`
                                                }]
                                            ]
                                        }
                                    })
                                });
                            })
                        })
                        .catch((error) => {
                            bot.sendMessage(msg.from.id, `<b>❌提现失败，请联系管理员处理！</b>`, {
                                parse_mode: 'HTML',
                            })
                        })
                }
            }
        });
    });
}

function quanbutixian(telegramid, chatid, messageid, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = '${telegramid}';`, (error, result) => {
            if (error) return error;
            connection.destroy();
            if (conf.txMin > result[0].yongjinbalance) {
                bot.answerCallbackQuery(callbackQueryid, {
                    text: `❌提现失败，未达到最低提现金额(${conf.txMin})！`,
                    show_alert: true,
                    cache_time: 1
                })
                return
            } else if (result[0].trx_address == "暂未绑定") {
                bot.answerCallbackQuery(callbackQueryid, {
                    text: `❌请先设置提现地址,发送地址即可自动绑定！`,
                    show_alert: true,
                    cache_time: 1
                })
                return
            } else {
                return
                var trx_address = result[0].trx_address;
                var txamount = (result[0].yongjinbalance * (1 - conf.txfee) / conf.utormb).toFixed(2)
                transferUSDT(result[0].trx_address, txamount)
                    .then(res => {
                        conf.pool.getConnection(function (err, connection) {
                            if (err) return err;
                            connection.query(`Insert into withdrawal (name, telegramid, amount, state, way, applytime,
                                                                      changetime, replyMessageid, hashid, trx_address)
                                              values ("${msg.from.username}", "${msg.from.id}", ${msg.text}, 1, "USDT",
                                                      now(), now(), ${msg.message_id}, "${hashid}", "${trx_address}");
                            update users
                            set balance = balance - ${msg.text}
                            where telegramid = "${msg.from.id}";`, (error, result) => {
                                connection.destroy();
                                if (error) return error;
                                bot.editMessageText(`<b>✅${txamount}USDT提现成功，请注意查收~</b>`, {
                                    chat_id: chatid,
                                    message_id: messageid,
                                    parse_mode: 'HTML',
                                    reply_markup: {
                                        inline_keyboard: [
                                            [{text: "查看详情", url: `https://tronscan.org/#/transaction/${hashid}`}]
                                        ]
                                    }
                                })
                            });
                        })
                    })
                    .catch((error) => {
                        bot.answerCallbackQuery(callbackQueryid, {
                            text: `❌提现失败，请联系管理员处理！`,
                            show_alert: true,
                            cache_time: 1
                        })
                    })
            }
        });
    });
}

function privatemain(msg) {

    if (msg.text.split(" ")[1] == "dlzx") {
        dailizhongxinstart(msg)
    } else if (msg.text.split(" ")[1] == "yxgz") {
        guizehuodong(msg)
    } else if (msg.text.split(" ")[1] == "fl") {
        fuli(msg)
    } else if (msg.text == "🏠代理中心") {
        dailizhongxin(msg)
    } else if (msg.text.search("/start") == 0) {
        start(msg)
    } else if (tronWeb.isAddress(msg.text)) {
        address(msg)
    } else if (msg.text == "游戏规则") {
        guizehuodong(msg)
    } else if (msg.text == "开始游戏") {
        kaishiyouxi(msg)
    } else if (msg.text == "最近投注") {
        zuijintouzhu(msg)
    } else if (msg.text == "账单记录") {
        zhangdanjilu(msg)
    } else if (msg.text == "个人中心") {
        usercenter(msg)
    } else if (msg.text == "我要充值") {
        chongzhi(msg)
    } else if (msg.text == "🏧佣金提现") {
        tixian(msg)
    } else if (parseInt(msg.text) % 1 == 0) {
        shuzi(msg);
    }
}

/*主函数，处理过滤完的文字消息 */
function main(msg) {
    console.log('-------主函数')
    if (resultArr) {
        console.log('-------主函数开盘')
        var nickname = guolvname((msg.from.first_name ? msg.from.first_name : "") + (msg.from.last_name ? msg.from.last_name : ""))
        console.log('-------主函数开盘', nickname)
        if (msg.text == "取消" || msg.text == "撤回") {
            // quanbuchehui(msg.text, msg.from.id, msg.from.username, msg.message_id)
            chehui(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.message_thread_id)
        } else if (msg.text.search("历史") != -1) {
            lishichaxun(msg.text, msg.from.id, msg.from.username, msg.message_id)
        } else if (msg.text == "2") {
            lishi(msg.text, msg.from.id, msg.from.username, msg.message_id)
        } else if (msg.text == "1" || msg.text == "余额") {
            benqitouzhutxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id, nickname)
        } else if (msg.text == "反水") {
            getReturnWatertxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
        } else if (msg.text == "输赢" || msg.text == "账单" || msg.text == "3" || msg.text == "查询") {
            getTodayBilltxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
        } else {
            bet(msg.text, msg.from.id, msg.from.username, msg.message_id, nickname);
        }
    }
}

function shangfenadmin(contant, telegramid, name, replyMessageid, username, fromusername, replyFromMessageid) {
    if (parseInt(contant.split('+')[1]) % 1 == 0 && contant.split('+')[0] == "" && !isNaN(Number(contant.split("+")[1], 10))) {

        conf.pool.getConnection(function (err, connection) {
            if (err) {
                return err;
            }
            connection.query(`SELECT *
                              FROM users
                              where telegramid = "${telegramid}";
            SELECT sum(amount)
            FROM pay
            where telegramid = "${telegramid}"
              and applytime > "${moment(Math.round(date) - 1000 * 60 * 60 * 24 * 7).format("YYYY-MM-DD HH:mm:ss")}";`, (error, result) => {
                if (error) return error;
                if (result[0][0]) {
                    var balance = result[0][0].balance;
                    var shangfensql = ""
                    if (balance <= 10) {
                        shangfensql = `update users
                                       set balance        = balance + ${contant.split("+")[1]},
                                           todaychongzhi  = todaychongzhi + ${contant.split("+")[1]},
                                           chongzhiamount = ${contant.split("+")[1]},
                                           liushui        = 0,
                                           lastpay_time   = now()
                                       where telegramid = "${telegramid}";`
                    } else {
                        shangfensql = `update users
                                       set balance        = balance + ${contant.split("+")[1]},
                                           todaychongzhi  = todaychongzhi + ${contant.split("+")[1]},
                                           chongzhiamount = chongzhiamount + ${contant.split("+")[1]},
                                           lastpay_time   = now()
                                       where telegramid = "${telegramid}";`
                    }

                    console.log(shangfensql)
                    connection.query(`select *
                                      from users
                                      where telegramid = "${result[0][0].inviter_telegramid}"; `, (error, r) => {
                        console.log(error)
                        if (error) return error;
                        connection.query(`${shangfensql}
                        Insert
                        into pay (telegramid,amount,state,way,applytime,replyMessageid) values ("${telegramid}",
                        ${contant.split("+")[1]},
                        1,
                        "群内管理上分",
                        now
                        (
                        ),
                        ${replyMessageid}
                        );`, (error, result) => {
                            connection.destroy();
                            console.log(error)

                            if (error) return error;
                            bot.sendMessage(conf.houtaiqunid, `✅充值成功\n\n账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a> \n上分：<code>${contant.split("+")[1]}</code>\n余额：<code>${(balance + parseFloat(contant.split("+")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`, {
                                parse_mode: "HTML"
                            })
                            bot.sendMessage(conf.chatid, `<b>📣<code>${name}</code>充值的 ${contant.split("+")[1]}RMB 已到账！</b>`, {
                                parse_mode: "HTML"
                            })
                            console.log('replyFromMessageid====', replyFromMessageid)
                            bot.sendPhoto(conf.sxfqunid, './img/shangfen.jpg', {
                                parse_mode: 'HTML',
                                disable_web_page_preview: true,
                                reply_to_message_id: replyMessageid,
                                caption: `${name}老板成功上分: ${contant.split("+")[1]} 元 \n➖➖➖➖➖➖➖➖➖➖\n♦️ 余额: ${(balance + parseFloat(contant.split("+")[1]))} 元\n恒旺集团上分模式📣\n支持🔥支付宝微信银行卡 💰\n支持🔥 USDT上分\n支持🔥福利来钱包上分  @ndjd7375`
                            })

                            console.log('date===============', date)
                            // if (date.getHours()!==19) {
                            /*                       bot.sendMessage(conf.jndqunid, `<b>📣<code>${name}</code>充值的 ${contant.split("+")[1]}RMB 已到账！</b>`, {
                                                       parse_mode: "HTML"
                                                   })*/
                            // }
                        });
                    });


                } else {
                    connection.destroy();
                }
            });
        })
    }
}


function qiandao(contant, telegramid, name, replyMessageid, fromid, chatid) {
    var sql = ""
    for (let index = 0; index < 7; index++) {
        sql += `select sum(amount)
                from pay
                where applytime like "${getlastday(index + 1)}"
                  and state = 1
                  and telegramid = "${telegramid}"; `
    }
    conf.pool.getConnection(function (err, connection) {
        connection.query(`SELECT *
                          FROM users
                          where telegramid = "${telegramid}";
        ${sql}
        select count(*)
        FROM pc_bet
        where type = '${conf.type}'
          and telegramid = "${telegramid}"
          and result is not null
          and time like "${moment(Math.round(new Date) - 1 * 60 * 60 * 24 * 1000).format("YYYY-MM-DD%")}"
          and amount >= 10; `, (error, result) => {
            if (error) throw error;
            if (!result[0][0]) {
                return
            }
            var zengsongjine = getqiandao(result)
            if (zengsongjine > 0 && result[8][0]['count(*)'] && result[0][0]['lastqiandao_time'].search(moment().format("YYYY-MM-DD")) == -1) {
                var balance = result[0][0].balance;
                /*if (zengsongjine==56 && result[0][0].qiandaoamount==7) {
                    zengsongjine = 6;
                }*/

                connection.query(`Insert into jiangli (telegramid, amount, type, time)
                                  values ("${telegramid}", ${zengsongjine}, "签到奖励", now());
                update users
                set balance          = balance + ${zengsongjine},
                    lastqiandao_time = now(),
                    chongzhiamount   = chongzhiamount + ${zengsongjine}
                where telegramid = "${telegramid}"`, (error, result) => {
                    connection.destroy();
                    console.log(error);
                    if (error) throw error;
                    bot.sendMessage(conf.houtaiqunid, `用户ID：<code>${telegramid}</code>\n用户名：<code>${name}</code> \n余额：<code>${balance}元</code>\n赠送签到奖励：<code>${zengsongjine}</code>`, {
                        parse_mode: "HTML"
                    })
                    bot.sendMessage(chatid, `<b>📣<code>${name}</code>的签到奖励 ${zengsongjine} ,已成功到账！</b>`, {
                        parse_mode: "HTML"
                    })
                });
            } else if (zengsongjine == 0) {
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)未满足充值条件，无法领取签到奖励</b>`, {
                    parse_mode: "HTML"
                })
            } else if (result[8][0]['count(*)'] + result[9][0]['count(*)'] + result[10][0]['count(*)'] < 10) {
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)未满足当日投注条件，无法领取签到奖励</b>`, {
                    parse_mode: "HTML"
                })
            } else if (result[0][0]['lastqiandao_time'].search(moment().format("YYYY-MM-DD") != -1)) {
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)今日已领取签到奖励，无法再次领取</b>`, {
                    parse_mode: "HTML"
                })
            } else {
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)不符合赠送条件，无法领取签到奖励</b>`, {
                    parse_mode: "HTML"
                })
            }
        });
    })
}

function getqiandao(result) {
    var fafangamount = 0
    console.log(result);
    for (let index = 1; index < result.length; index++) {
        if (result[index][0]['sum(amount)'] > 500) {
            if (index == 1) {
                fafangamount = fafangamount + 6
            } else if (index == 2) {
                fafangamount = fafangamount + 6
            } else if (index == 3) {
                fafangamount = fafangamount + 6
            } else if (index == 4) {
                fafangamount = fafangamount + 10
            } else if (index == 5) {
                fafangamount = fafangamount + 10
            } else if (index == 6) {
                fafangamount = fafangamount + 10
            } else if (index == 7) {
                fafangamount = fafangamount + 10
            }
        } else {
            return fafangamount
        }
    }
    return fafangamount
}


function yongjintixian(contant, telegramid, name, replyMessageid, username, fromusername, chatid) {
    if (parseInt(contant.split('yj')[1]) % 1 == 0 && contant.split('yj')[0] == "" && !isNaN(Number(contant.split("yj")[1], 10))) {
        conf.pool.getConnection(function (err, connection) {
            connection.query(`SELECT *
                              FROM users
                              where telegramid = "${telegramid}";`, (error, result) => {
                if (error) return error;
                if (result.length == 0) {
                    connection.destroy();
                    bot.sendMessage(conf.sxfqunid, `<b>❌佣金余额不足，提现发起失败！</b>`, {
                        parse_mode: "HTML"
                    })
                        .then(res => {
                            setTimeout(function (params) {
                                bot.deleteMessage(conf.sxfqunid, res.message_id)
                            }, 180000)
                        })
                } else {

                    var userinfo = result[0];
                    if (userinfo.yongjinbalance < parseFloat(contant.split("yj")[1])) {
                        connection.destroy();
                        bot.sendMessage(conf.sxfqunid, `<b>❌当前可提现佣金 ${userinfo.yongjinbalance}，提现发起失败！</b>`, {
                            parse_mode: "HTML"
                        })
                            .then(res => {
                                setTimeout(function (params) {
                                    bot.deleteMessage(conf.sxfqunid, res.message_id)
                                }, 180000)
                            })
                    } else {
                        connection.query(`select *
                                          from users
                                          where telegramid = "${userinfo.inviter_telegramid}";
                        update users
                        set yongjinbalance = yongjinbalance - ${contant.split("yj")[1]}
                        where telegramid = "${telegramid}"`, (error, result) => {
                            connection.destroy();
                            if (error) return error;
                            console.log('=========', error)
                            bot.sendMessage(-932657331, `✅佣金提现成功\n\n${(result[0][0] ? `上级：<a href="https://t.me/${result[0][0].name}">${result[0][0].nickname}</a>\n` : "")}账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a>\n佣金：<code>${contant.split("yj")[1]}</code>\n余额：<code>${(userinfo.yongjinbalance - parseFloat(contant.split("yj")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`, {
                                parse_mode: "HTML"
                            })
                            bot.sendMessage(conf.chatid, `<b>💎代理 <code>${name}</code>,${contant.split("yj")[1]}请查收！</b>`, {
                                parse_mode: "HTML"
                            })
                        });
                    }

                }
            });
        })
    }
}

function xiafenadmin(contant, telegramid, name, replyMessageid, username, fromusername, chatid) {
    if (parseInt(contant.split('-')[1]) % 1 == 0 && contant.split('-')[0] == "" && !isNaN(Number(contant.split("-")[1], 10))) {
        conf.pool.getConnection(function (err, connection) {
            connection.query(`SELECT *
                              FROM users
                              where telegramid = "${telegramid}";`, (error, result) => {
                console.log(error)
                if (error) return error;
                if (result.length == 0) {
                    connection.destroy();
                    bot.sendMessage(conf.sxfqunid, `<b>❌余额不足，提现发起失败！</b>`, {
                        parse_mode: "HTML"
                    })
                        .then(res => {
                            setTimeout(function (params) {
                                bot.deleteMessage(conf.sxfqunid, res.message_id)
                            }, 180000)
                        })
                } else {
                    var userinfo = result[0];
                    connection.query(`select sum(amount)
                                      FROM pc_bet
                                      where type = '${conf.type}'
                                        and telegramid = "${telegramid}"
                                        and time
                                          > "${userinfo.lastpay_time}"
                                        and result is not NULL;`, (error, result) => {
                        console.log(error)
                        if (error) return error;
                        if (userinfo.balance < parseFloat(contant.split("-")[1])) {
                            connection.destroy();
                            bot.sendMessage(conf.sxfqunid, `<b>❌当前可提现余额 ${userinfo.balance}，提现发起失败！</b>`, {
                                parse_mode: "HTML"
                            })
                                .then(res => {
                                    setTimeout(function (params) {
                                        bot.deleteMessage(conf.sxfqunid, res.message_id)
                                    }, 180000)
                                })
                        } else if (userinfo.liushui < userinfo.chongzhiamount * conf.shui) {
                            connection.destroy();
                            bot.sendMessage(conf.sxfqunid, `<b>❌当前流水${userinfo.liushui}，需大于 ${userinfo.chongzhiamount * conf.shui} 后，方可提现!</b>`, {
                                parse_mode: "HTML"
                            })
                                .then(res => {
                                    setTimeout(function (params) {
                                        bot.deleteMessage(conf.sxfqunid, res.message_id)
                                    }, 180000)
                                })
                            return
                        } else {
                            connection.query(`Insert into withdrawal (telegramid, amount, state, way, applytime, replyMessageid)
                                              values ("${telegramid}", ${contant.split("-")[1]}, 1, "群内管理下分",
                                                      now(), ${replyMessageid});
                            update users
                            set balance        = balance - ${contant.split("-")[1]},
                                chongzhiamount = 0,
                                liushui        = 0
                            where telegramid = "${telegramid}"`, (error, result) => {
                                connection.destroy();
                                console.log(error)
                                if (error) return error;

                                bot.sendPhoto(conf.sxfqunid, "./img/xiafen.jpg", {
                                    parse_mode: "HTML",
                                    caption: `🎉恭喜【${name}】老板在恒旺集团【快三】下分${contant.split("-")[1]}元成功，恭祝老板：日进斗金  天天嫩模 天天提款🧨🧨🧨`
                                })
                                bot.sendMessage(conf.houtaiqunid, `✅提现成功\n\n账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a>\n下分：<code>${contant.split("-")[1]}</code>\n余额：<code>${(userinfo.balance - parseFloat(contant.split("-")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`, {
                                    parse_mode: "HTML"
                                })
                                bot.sendMessage(conf.chatid, `<b>💎贵宾 <code>${name}</code>,${contant.split("-")[1]}请查收！</b>`, {
                                    parse_mode: "HTML"
                                })
                            });
                        }
                    });

                }
            });
        })
    }
}

function checkarray(item, array) {

    for (let index = 0; index < array.length; index++) {
        if (array[index] == item) {
            return true
        }

    }
    return false;
}

function sxf(msg) {
    if (msg.text.search("上分") != -1) {
        shangfen(msg.text, msg.from.id, msg.from.username, msg.message_id)
    } else if (msg.text.search("下分") != -1) {
        xiafen(msg.text, msg.from.id, msg.from.username, msg.message_id)
    } else if (msg.text == "1") {
        yuetxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
    } else if (msg.text.search("/zjtz") != -1) {
        getMyBettxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
    } else if (msg.text == "输赢" || msg.text == "账单" || msg.text == "3" || msg.text == "查询") {
        getTodayBilltxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
    } else if (msg.text.search("/lqfs") != -1) {
        getReturnWatertxt(msg.text, msg.from.id, msg.from.username, msg.message_id, msg.chat.id)
    }
}

/*上分*/
function shangfen(contant, telegramid, name, replyMessageid) {
    bot.sendMessage(conf.sxfqunid, `人民币上下分•100元起
USDT上下分•15U起

🔥上分支持-微信-支付宝-银行卡-USDT

充值上分找客服：@ndjd7375

⚠️认准客服ID，主动私聊你一定是骗子！

转账后私发截图给客服，通过审核后会第一时间上分。

🌟USDT上分地址: 

<code>TWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd</code>

点击U地址（自动复制）
认准U地址：ws21s3g结尾

⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！
⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！
⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！`, {
        reply_to_message_id: replyMessageid,
        parse_mode: 'HTML',
        reply_markup: {
            inline_keyboard: conf.tixian_inline_keyboard
        },
        disable_web_page_preview: true
    })
}

/*下分*/
function xiafen(contant, telegramid, name, replyMessageid) {
    return
    if (parseInt(contant.split('下分')[1]) % 1 == 0 && contant.split('下分')[0] == "" && !isNaN(Number(contant.split("下分")[1], 10))) {
        conf.pool.getConnection(function (err, connection) {
            connection.query(`SELECT *
                              FROM users
                              where telegramid = "${telegramid}";
            SELECT SUM(amount)
            FROM pc_bet
            where type = '${conf.type}'
              and telegramid = "${telegramid}"
              and resultid = "${resultid}";`, (error, result) => {
                if (error) return error;
                if (result.length == 0) {
                    bot.sendMessage(conf.sxfqunid, `余额不足，提现失败！`, {
                        reply_to_message_id: replyMessageid
                    })
                } else {
                    var balance = result[0][0].balance;
                    if (balance >= parseFloat(contant.split("下分")[1])) {
                        connection.query(`Insert into withdrawal (name, telegramid, amount, state, way, applytime, replyMessageid)
                                          values ("${name}", "${telegramid}", ${contant.split("下分")[1]}, 0,
                                                  "群内下分", now(), ${replyMessageid});
                        update users
                        set balance = balance - ${contant.split("下分")[1]}
                        where telegramid = "${telegramid}"`, (error, result) => {
                            connection.destroy();
                            if (error) return error;
                            bot.sendMessage(conf.sxfqunid, `账号:${telegramid}\n用户名：${name} \n余额：${(balance - parseFloat(contant.split("下分")[1])).toFixed(2)}元\n您的下分申请提交成功，请勿重复提交，审核通过后第一时间下分`, {
                                reply_to_message_id: replyMessageid
                            })
                        });
                    } else {
                        bot.sendMessage(conf.sxfqunid, `余额不足，提现失败！`, {
                            reply_to_message_id: replyMessageid
                        })
                    }
                }
            });
        })
    }
}

/*发送即将封盘提醒*/
function fengpantixing() {
    bot.sendMessage(conf.chatid, `<b>⏰封盘提醒 :\n\n<code>${resultid}</code>期距离封盘还剩30秒！</b>`, {
        parse_mode: "HTML"
    })
        .then(res => {
            fengpancishu++
        })
        .catch(err => {
            console.log(err);

        })
}


/*查询开奖历史*/
function lishichaxun(contant, telegramid, name, replyMessageid) {
    if (parseInt(contant.split('历史')[1]) % 1 != 0 || parseInt(contant.split('历史')[1]) < 0 || isNaN(Number(contant.split("历史")[1], 10))) {
        return
    }
    var qishu = 0;
    if (parseInt(contant.split('历史')[1]) > 50) {
        qishu = 10
    } else {
        qishu = parseInt(contant.split('历史')[1])
    }
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_result
                          WHERE type = '${conf.type}'
                          ORDER by result_time desc limit ${qishu};`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var historylist = "";
            for (let index = 0; index < result.length; index++) {
                let item = result[index]
                historylist += `${item.id}期 <code>${item.one} ${item.two} ${item.three} = ${item.one + item.two + item.three}  ${item.big == 1 ? '大' : ''} ${item.small == 1 ? '小' : ''} ${item.odd == 1 ? '单' : ''} ${item.even == 1 ? '双' : ''} ${item.baozi == 1 ? '豹子' : ''} ${item.shunzi == 1 ? '顺子' : ''} ${item.duizi == 1 ? '对子' : ''} ${item.jida == 1 ? '极大' : ''} ${item.jixiao == 1 ? '极小' : ''}</code>  \n`
            }
            bot.sendMessage(conf.chatid, `<code>------ 历史开奖 -----</code>\n${historylist}<code>---------------------------</code>`, {
                reply_to_message_id: replyMessageid,
                parse_mode: "HTML"
            })
        });
    });
}


/*查询开奖历史*/
function lishi(contant, telegramid, name, replyMessageid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_result
                          where type = '${conf.type}'
                            and three is not null
                          ORDER by result_time desc limit 10;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var historylist = "";
            for (let index = 0; index < result.length; index++) {
                let item = result[index]
                historylist += `${item.id}期 <code>${item.one} ${item.two} ${item.three} = ${item.one + item.two + item.three}  ${item.big == 1 ? '大' : ''} ${item.small == 1 ? '小' : ''} ${item.odd == 1 ? '单' : ''} ${item.even == 1 ? '双' : ''} ${item.baozi == 1 ? '豹子' : ''} ${item.shunzi == 1 ? '顺子' : ''} ${item.duizi == 1 ? '对子' : ''} ${item.jida == 1 ? '极大' : ''} ${item.jixiao == 1 ? '极小' : ''}</code>  \n`
            }
            bot.sendMessage(conf.chatid, `<code>------ 历史开奖 -----</code>\n${historylist}<code>---------------------------</code>`, {
                reply_to_message_id: replyMessageid,
                parse_mode: "HTML"
            })
        });
    });
}

/*取消单个*/
function chehui(contant, telegramid, name, replyMessageid, message_thread_id) {
    let resultid = resultArr[0].qishu
    if (isfengpan) {
        bot.sendMessage(conf.chatid, `取消失败！\n原因:已经封盘`, {
            reply_to_message_id: replyMessageid
        })
        return
    }
    /* if (!message_thread_id) {
         bot.sendMessage(conf.chatid, `无法获取消息的回复id，请使用“全部取消”功能！`, {
             reply_to_message_id: replyMessageid
         })
         return
     }*/
    var chehuisql = "";
    var chehuiorder = "";
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = "${telegramid}"
                            and resultid = "${resultid}";`, (error, result) => {
            if (error) return error;
            for (let index = 0; index < result.length; index++) {
                chehuiorder = `${chehuiorder}${result[index].guess}-${result[index].amount}\n`
                chehuisql = `${chehuisql}
                DELETE
                FROM pc_bet
                where type = '${conf.type}'
                  and id = '${result[index].id}';
                UPDATE users
                set balance = balance + ${result[index].amount}
                where telegramid = "${result[index].telegramid}"; `
            }
            if (result.length == 0) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `取消失败！\n原因:已经开奖`, {
                    reply_to_message_id: replyMessageid
                })
            } else {
                connection.query(chehuisql, (error, result) => {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(conf.chatid, `取消成功！\n包含的投注有：\n${chehuiorder}`, {
                        reply_to_message_id: replyMessageid
                    })
                });
            }

        });
    });
}

/*文字消息查看余额*/
function yuetxt(contant, telegramid, name, replyMessageid, chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = "${telegramid}";`, (error, result) => {
            connection.destroy();
            if (error) return error;
            if (result[0]) {
                var txstate = ""
                if (result[0].liushui >= result[0].chongzhiamount * conf.shui) {
                    txstate = "✅可提现"
                } else {
                    txstate = "❌流水未达标"
                }
                //佣金：<code>${result[0].yongjinbalance}</code>\n
                bot.sendMessage(chatid, `<b>用户信息</b>\n账号：<code>${result[0].telegramid}</code>\n昵称：<code>${entitiestoUtf16(result[0].nickname)}</code>\n余额：<code>${result[0].balance}元</code>\n\n<b>流水检测</b>\n流水：<code>${result[0].liushui}元</code>\n${txstate}`, {
                    reply_to_message_id: replyMessageid,
                    parse_mode: "HTML",
                    reply_markup: {
                        inline_keyboard: conf.tixian_inline_keyboard
                    },
                })
                    .then(res => {
                        setTimeout(function (params) {
                            bot.deleteMessage(res.chat.id, res.message_id)
                        }, 180000)
                    })
            }
        });
    });

}


/*文字消息查看余额*/
function benqitouzhutxt(contant, telegramid, name, replyMessageid, chatid, firstname) {
    let resultid = resultArr[0].qishu
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = "${telegramid}";
        select *
        FROM pc_bet
        where type = '${conf.type}'
          and telegramid = "${telegramid}"
          and resultid = "${resultid}"
          and result is null
        ORDER BY time DESC;`, (error, result) => {
            connection.destroy();
            console.log(error)
            if (error) return error;
            if (result[0].length == 0) {
                bot.sendMessage(chatid, `👤${firstname}   💰余额：0.00元`, {
                    reply_to_message_id: replyMessageid
                })
            } else if (!result[1][0]) {
                bot.sendMessage(chatid, `\n\n👤${firstname} \n💰余额：${(result[0][0].balance)}元`, {
                    reply_to_message_id: replyMessageid,
                    parse_mode: "HTML"
                })
            } else {
                var quanbutouzhu = "";
                for (var index = 0; index < result[1].length; index++) {
                    quanbutouzhu += `<code>${result[1][index].guess}</code>-<code>${result[1][index].amount}</code>(<code>${result[1][index].peilv}</code>倍赔率)\n`
                }
                let returnMsg = `玩家：${firstname}\n \n ✅已投注\n ${quanbutouzhu} \n \n 余额：${(result[0][0].balance)} 元`
                bot.sendMessage(conf.chatid, returnMsg, {
                    reply_to_message_id: replyMessageid,
                    parse_mode: "HTML"
                })
            }
        });

    });

}

/*文字消息查询我的投注记录*/
function getMyBettxt(contant, telegramid, name, replyMessageid, chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = '${telegramid}'
                          order by id desc LIMIT 10;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (result[index].resultid == resultid) {
                    result_money = `待开奖`
                } else if (result[index].result == 0) {
                    result_money = `未中奖`
                } else {
                    result_money = `中奖${result[index].result.toFixed(2)}${conf.coin[0]}`
                }
                myBet = `${myBet} ${result[index].resultid}期：${result[index].guess}${result[index].amount.toFixed(2)}${conf.coin[0]}-${result_money}\n`;
            }
            bot.sendMessage(chatid, `最近投注记录：\n${myBet}`, {
                reply_to_message_id: replyMessageid
            })
        });
    });
}

/*文字消息查询流水*/
function getTodayBilltxt(contant, telegramid, name, replyMessageid, chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = "${telegramid}"
                            and time LIKE CONCAT(CURDATE()
                              , '%');`, (error, result) => {
            console.log(error)
            if (error) return error;
            connection.destroy();
            var todayWin = 0;
            var todayPurchase = 0;
            var todayWaitResult = 0;
            for (let index = 0; index < result.length; index++) {
                if (resultid != result[index].resultid) {
                    todayWin = todayWin + result[index].result - result[index].amount + result[index].amountreturn;
                    todayPurchase = todayPurchase + result[index].amount;
                    console.log('result[index].amount====', result[index].amount)
                } else {
                    todayWaitResult = todayWaitResult + result[index].amount;
                }
                console.log('todayPurchase======', todayPurchase)
            }
            bot.sendMessage(chatid, `待结算：${todayWaitResult.toFixed(2)} ${conf.coin}\n今日输赢：${todayWin.toFixed(2)} ${conf.coin}\n今日总流水：${todayPurchase.toFixed(2)} ${conf.coin}`, {
                reply_to_message_id: replyMessageid
            })
        });
    });
}

/*文字消息领取反水*/
function getReturnWatertxt(contant, telegramid, name, replyMessageid, chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = "${telegramid}"
                            and isreturn = 0
                            and resultid != ${resultid};`, (error, result) => {
            if (error) return error;
            var myReturnWater = 0;
            for (let index = 0; index < result.length; index++) {
                myReturnWater = myReturnWater + result[index].amount * conf.returnWater;
            }
            if (parseInt(myReturnWater) < 1) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `<b>❌可领取反水小于1，无法领取</b>`, {
                    reply_to_message_id: replyMessageid,
                    parse_mode: "HTML"
                })
                return
            } else {
                connection.query(`select *
                                  from users
                                  where telegramid = "${telegramid}";
                UPDATE users
                set balance = balance + ${parseInt(myReturnWater)}
                where telegramid = "${telegramid}";
                update pc_bet
                set isreturn     = 1,
                    amountreturn = amount * ${conf.returnWater}
                where type = ${conf.type}
                  and telegramid = "${telegramid}"
                  and resultid != "${resultid}";`, (error, result) => {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(chatid, `<b>流水金额：<code>${parseInt(myReturnWater / conf.returnWater)}</code>\n反水比例：<code>${conf.returnWater * 100}%</code>\n反水金额：<code>${parseInt(myReturnWater)}</code> \n\n当前余额：<code>${(result[0][0].balance + parseInt(myReturnWater))}元</code></b>`, {
                        reply_to_message_id: replyMessageid,
                        parse_mode: "HTML"
                    })

                });
            }

        });
    });
}

function guolvname(name) {
    var namestr = name.substring(0, 10);
    var newname = ""
    var wjz = ["$", "<", ">", "{", "}", "\""]
    for (let index = 0; index < namestr.length; index++) {
        var iswjz = false
        for (let a = 0; a < wjz.length; a++) {
            if (namestr[index] == wjz[a]) {
                iswjz = true
            }
        }
        if (!iswjz) {
            newname += namestr[index]
        }

    }
    return newname
}

/*全部取消*/
function quanbuchehui(contant, telegramid, name, replyMessageid) {
    var chehuisql = "";
    var chehuiorder = "";
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = "${telegramid}"
                            and resultid = ${resultid};`, (error, result) => {
            if (error) return error;
            if (result.length == 0) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `<b>❌您当期暂无任何投注！</b>`, {
                    reply_to_message_id: replyMessageid,
                    parse_mode: "HTML"
                })
            } else {
                for (let index = 0; index < result.length; index++) {
                    chehuiorder = `${chehuiorder}${result[index].guess}-${result[index].amount}\n`
                    chehuisql = `${chehuisql}
                    DELETE
                    FROM pc_bet
                    where type = '${conf.type}'
                      and id = '${result[index].id}';
                    UPDATE users
                    set balance = balance + ${result[index].amount}
                    where telegramid = "${result[index].telegramid}"; `
                }
                connection.query(chehuisql, (error, rr) => {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(conf.chatid, `<b>🔙${result[0].resultid}期投注已取消！</b>`, {
                        reply_to_message_id: replyMessageid,
                        parse_mode: "HTML"
                    })
                });
            }
        });
    });

}

/*设置开奖期数*/
function setResultID() {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT COUNT(*)
                          FROM pc_result
                          WHERE type = '${conf.type}'
                            and result_time LIKE CONCAT(CURDATE(), '%');`, (error, result) => {
            console.log(error)
            if (error) return error;

            connection.query(`insert into pc_result (id, result_time, type)
                              VALUES ("${resultid}", now(), ${conf.type});`, (error, result) => {
                console.log(error)
                if (error) return error;
                connection.destroy();
                startBet()
            })
            console.log('初始化resultid===========', resultid)


        });
    });

}

/*查询用户余额*/
function getBalance(telegramid, name, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = '${telegramid}';`, (error, result) => {
            if (error) return error;
            console.log("yonghuyue", name);
            if (result.length == 0) {
                connection.query(`Insert into users (name, telegramid, register_time)
                                  values ('${name}', '${telegramid}', now());`, (error, result) => {
                    connection.destroy();
                    if (error) return error;
                    bot.answerCallbackQuery(callbackQueryid, {
                        text: `余额：0元`,
                        show_alert: true,
                        cache_time: 10
                    })
                });
            } else {
                connection.destroy();
                bot.answerCallbackQuery(callbackQueryid, {
                    text: `余额：${result[0].balance}元`,
                    show_alert: true,
                    cache_time: 10
                })
            }
        });
    });
}

/*查询我的投注记录*/
function getMyBet(telegramid, name, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and telegramid = '${telegramid}'
                            and result > 0
                          order by id desc LIMIT 5;`, (error, result) => {
            if (error) return error;
            console.log("touzhujilu", name);
            connection.destroy();
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (!result[index].result) {
                    result_money = `⏰`
                } else if (result[index].result == 0) {
                    result_money = `❌`
                } else {
                    result_money = `✅`
                }
                myBet = `${myBet}${result_money} ${result[index].resultid}-${result[index].guess}-${result[index].amount}\n`;
            }
            bot.answerCallbackQuery(callbackQueryid, {
                text: `${myBet}`,
                show_alert: true,
                cache_time: 10
            })

        });
    });
}

/*开始下注*/
function startBet() {

    console.log('========开始下注==============')
    // 开奖
    let next = resultArr[0].next
    // resultid = parseBody.issue[0].qishu
    // fengpantime = moment(parseInt(next + '000') + (1000 * 60 * 3) + (1000 * 20)).format("HH:mm:ss")
    // kaijiangtime = moment(parseInt(next + '000') + (1000 * 60 * 3) + (1000 * 30)).format("HH:mm:ss")
    // console.log('fengpantime=====', fengpantime)
    // console.log('kaijiangtime=====', kaijiangtime)

    // let msg = `🚨 ${resultid}期 开始投注\n 封盘时间  ${fengpantime}\n 开奖时间  ${kaijiangtime}\n------------------------------------\n 大小单双投注金额为5-20000rmb\n 大双小双大单小单投注金额5-10000rmb`;


    let msg = `🚨 ${resultid}期 开始投注\n------------------------------------\n加拿大2.8  pc28\n下注格式为：单1000 大单2000\n押单数格式为：数字+押+金额：例10押100\n—— —— —— —— —— —— —— ——\n🏆玩法限额/赔率：\n♦️大小单双（10-10W）\n♦️组合（10-10W）\n♦️数字（10-2000）\n🔹对子（10-300）3倍\n🔹顺子（10-300）11倍\n🔹豹子（10-100）60倍\n🔹极值（10-300）15倍\n🔥大小单双 2.8倍🔸小单大双6.0倍🔸大单小双 6.0倍\n⚠️遇13/14 、对子、顺子、豹子 回本\n（注：开出890/190等三个数字均为顺子）\n—— —— —— —— —— —— —— ——\n0/27=500倍   💵  1/26=120倍\n2/25=98倍     💵  3/24=58倍\n4/23=48倍     💵  5/22=32倍\n6/21=25倍     💵  7/20=20倍\n8/19=17倍     💵  9/18=15倍\n10/17=14倍   💵  11/16=13倍\n12/15=12倍   💵  13/14=10倍\n—— —— —— —— —— —— —— ——\n游戏规则\n因为接口问题和卡BUG问题（退回本金重新下注）\n\n🔥游戏规则：\n⚠️本群下注无任何限制！\n\n🈲🈲主动私信上分的都是骗子,以机器人录入结算为准！\n凡是游戏程序出错期间,利用bug进行套利的，我方有权扣除盈利部分，只返还本金\n\n以上活动最终解释权归【鑫达聚】所有！\n🔥总注10万封顶❗️ \n🔥【反水】立即派送❗️\n🔰🔰🔰🔰🔰🔰🔰🔰🔰`


    bot.sendPhoto(conf.chatid, ksxz, {
        parse_mode: "HTML",
        disable_web_page_preview: true,
        caption: msg
    }).then(res => {
        console.log('==================设置开盘状态关闭====================')
        isfengpan = falsea = 0
        b = 0
        c = 0
    })

}

/*封盘*/
function getAllBet() {
    console.log('封盘=====================')
    let resultid = resultArr[0].qishu
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`update gamestate
                          set state = 1
                          where game = 'ks';`, (error, result) => {
            if (error) return error;
            connection.destroy();
        });
    });
    conf.pool.getConnection(function (err, connection) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('resultid======', resultid)
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and resultid = "${resultid}"
                          order by telegramid desc;`, (error, result) => {
            if (error) {
                console.log(error);
                return;
            }
            console.log('封盘总投注人数====', result)
            connection.destroy()
            var AllBet = ``;
            for (let index = 0; index < result.length; index++) {
                AllBet = `${AllBet}\n${entitiestoUtf16(result[index].firstname)} <code>${result[index].guess}(${result[index].amount})(${result[index].peilv}倍赔率)</code>`;
            }
            if (AllBet.length > 900) {
                AllBet = ""
                for (let index = 0; index < 20; index++) {
                    AllBet = `${AllBet}\n${entitiestoUtf16(result[index].firstname)} <code>${result[index].guess}(${result[index].amount})(${result[index].peilv}倍赔率)</code>`;
                }
                AllBet += `\n等${result.length}次投注`
            }

            console.log('AllBet=====', AllBet)
            console.log('result=====', result)

            resultArray = result;
            var fengpanresulttxt = `<b><code>${resultid}</code>期</b>\n<b>— — — — - 封盘线 - — — — —</b>${AllBet}\n\n<b>— 已封盘,线上下注全部有效 —</b>`;
            if (conf.sendmode == "t") {
                bot.sendMessage(conf.chatid, fengpanresulttxt, {
                    parse_mode: "HTML",
                    reply_markup: JSON.stringify({
                        inline_keyboard: conf.inline_keyboard
                    })
                })
                    .then(res => {
                        isfengpan = true
                    })
                    .catch(e => {
                        console.log(e);
                    });
            } else if (conf.sendmode == "pt") {
                bot.sendPhoto(conf.chatid, tzxz, {
                    parse_mode: "HTML",
                    disable_web_page_preview: true,
                    caption: fengpanresulttxt
                })
                    .then(res => {
                        isfengpan = true;
                        console.log('==============设置开盘状态开启==============')
                        fashazi()
                    })
                    .catch(e => {
                        console.log('发送图片错误======', e);

                        conf.pool.getConnection(function (err, connection) {
                            if (err) return err;
                            connection.query(`update gamestate
                                              set state = 1
                                              where game = 'ks';`, (error, result) => {
                                if (error) return error;
                                connection.destroy();
                            });
                        });
                    });
            }
        });
    });
}

/*下注*/
function bet(contant, telegramid, name, replyMessageid, firstname) {
    console.log('========开始下注===========================')
    var shuzisql = ""
    let resultid = resultArr[0].qishu
    if (isfengpan) {
        bot.sendMessage(conf.chatid, `<b>❌慢！本期已封盘 , 投注无效！</b>`, {
            reply_to_message_id: replyMessageid,
            parse_mode: "HTML"
        })
        connection.destroy();
        return;
    }
    for (let index = 0; index < 28; index++) {
        shuzisql += `select sum(amount)
                     FROM pc_bet
                     where type = '${conf.type}'
                       and telegramid = "${telegramid}"
                       and resultid = "${resultid}"
                       and guess = "押${index}点";`
    }
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        console.log('err====', err)
        connection.query(
            `SELECT *
             FROM users
             where telegramid = "${telegramid}";
            ${shuzisql}
            SELECT COUNT(*)
            FROM pc_result
            WHERE type = '${conf.type}'
              and result_time LIKE CONCAT(CURDATE(), '%');
            SELECT *
            FROM pc_bet
            WHERE type = '${conf.type}'
              and telegramid = "${telegramid}"
              and one is null;
            SELECT *
            FROM pc_result
            WHERE type = '${conf.type}'
              and telegramid = "${telegramid}"
              and one is not null
              and three is null
              and result_time > "${moment(Math.round(date) - 300000).format("YYYY-MM-DD HH:mm:ss")}";`, (error, result) => {
                console.log('error====', error)
                if (error) return error;
                var isnertresultsql = ""
                console.log(result[16][0] == undefined);
                console.log('result[16][0]===========', result[16][0])
                /*if (!result[16][0]) {
                     resultid = moment(date).format("YYYYMMDD") + (result[15][0]['COUNT(*)'])
                     isnertresultsql = `insert into pc_result (id, result_time, telegramid)
                                        VALUES ("${resultid}", now(), "${telegramid}");`
                } else {
                    resultid = result[16+14][0].resultid
                }
*/
                if (result[17 + 14][0]) {
                    bot.sendMessage(conf.chatid, `<b>❌您还有投注未完成，无法继续投注</b>`, {
                        parse_mode: "HTML"
                    })
                    return
                }
                var userBalance = result[0][0].balance;
                var userinfo = result[0][0];
                var xiazhujine = 0;
                var baozi_xiazhujine = 0;
                var shabaozi_xiazhujine = 0;
                var shuzi_xiazhujine = 0;
                var shuziamount = {
                    "押0点": (result[1][0]['sum(amount)'] ? result[1][0]['sum(amount)'] : 0),
                    "押1点": (result[1 + 1][0]['sum(amount)'] ? result[1 + 1][0]['sum(amount)'] : 0),
                    "押2点": (result[2 + 1][0]['sum(amount)'] ? result[2 + 1][0]['sum(amount)'] : 0),
                    "押3点": (result[3 + 1][0]['sum(amount)'] ? result[3 + 1][0]['sum(amount)'] : 0),
                    "押4点": (result[4 + 1][0]['sum(amount)'] ? result[4 + 1][0]['sum(amount)'] : 0),
                    "押5点": (result[5 + 1][0]['sum(amount)'] ? result[5 + 1][0]['sum(amount)'] : 0),
                    "押6点": (result[6 + 1][0]['sum(amount)'] ? result[6 + 1][0]['sum(amount)'] : 0),
                    "押7点": (result[7 + 1][0]['sum(amount)'] ? result[7 + 1][0]['sum(amount)'] : 0),
                    "押8点": (result[8 + 1][0]['sum(amount)'] ? result[8 + 1][0]['sum(amount)'] : 0),
                    "押9点": (result[9 + 1][0]['sum(amount)'] ? result[9 + 1][0]['sum(amount)'] : 0),
                    "押10点": (result[10 + 1][0]['sum(amount)'] ? result[10 + 1][0]['sum(amount)'] : 0),
                    "押11点": (result[11 + 1][0]['sum(amount)'] ? result[11 + 1][0]['sum(amount)'] : 0),
                    "押12点": (result[12 + 1][0]['sum(amount)'] ? result[12 + 1][0]['sum(amount)'] : 0),
                    "押13点": (result[13 + 1][0]['sum(amount)'] ? result[13 + 1][0]['sum(amount)'] : 0),
                    "押14点": (result[14 + 1][0]['sum(amount)'] ? result[14 + 1][0]['sum(amount)'] : 0),
                    "押15点": (result[15 + 1][0]['sum(amount)'] ? result[15 + 1][0]['sum(amount)'] : 0),
                    "押16点": (result[16 + 1][0]['sum(amount)'] ? result[16 + 1][0]['sum(amount)'] : 0),
                    "押17点": (result[17 + 1][0]['sum(amount)'] ? result[17 + 1][0]['sum(amount)'] : 0),
                    "押18点": (result[18 + 1][0]['sum(amount)'] ? result[18 + 1][0]['sum(amount)'] : 0),
                    "押19点": (result[19 + 1][0]['sum(amount)'] ? result[19 + 1][0]['sum(amount)'] : 0),
                    "押20点": (result[20 + 1][0]['sum(amount)'] ? result[20 + 1][0]['sum(amount)'] : 0),
                    "押21点": (result[21 + 1][0]['sum(amount)'] ? result[21 + 1][0]['sum(amount)'] : 0),
                    "押22点": (result[22 + 1][0]['sum(amount)'] ? result[22 + 1][0]['sum(amount)'] : 0),
                    "押23点": (result[23 + 1][0]['sum(amount)'] ? result[23 + 1][0]['sum(amount)'] : 0),
                    "押24点": (result[24 + 1][0]['sum(amount)'] ? result[24 + 1][0]['sum(amount)'] : 0),
                    "押25点": (result[25 + 1][0]['sum(amount)'] ? result[25 + 1][0]['sum(amount)'] : 0),
                    "押26点": (result[26 + 1][0]['sum(amount)'] ? result[26 + 1][0]['sum(amount)'] : 0),
                    "押27点": (result[27 + 1][0]['sum(amount)'] ? result[27 + 1][0]['sum(amount)'] : 0),
                }
                var xiazhujinearray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //d x d s dd xd ds xs jida jixiao he shunzi duizi shadian
                console.log('contant=====', contant)
                if (contant.search("哈") != -1 && contant.split("哈").length == 2) {
                    if (contant.split("哈")[0] == "" || contant.split("梭哈")[0] == "") {
                        amount = userBalance;
                        guess = contant.split("哈")[1];
                        peilv = 0;
                        if (contant.split("哈")[1] == "大") {
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[0] += amount
                        }
                        if (contant.split("哈")[1] == "小") {
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[1] += amount
                        }
                        if (contant.split("哈")[1] == "单") {
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[2] += amount
                        }
                        if (contant.split("哈")[1] == "双") {
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[3] += amount
                        }
                        if (contant.split("哈")[1] == "大单") {
                            peilv = conf.peilv['fushi1'];
                            xiazhujinearray[4] += amount
                        }
                        if (contant.split("哈")[1] == "小双") {
                            peilv = conf.peilv['fushi1'];
                            xiazhujinearray[7] += amount
                        }
                        if (contant.split("哈")[1] == "小单") {
                            peilv = conf.peilv['fushi2'];
                            xiazhujinearray[5] += amount
                        }
                        if (contant.split("哈")[1] == "大双") {
                            peilv = conf.peilv['fushi2'];
                            xiazhujinearray[6] += amount
                        }
                        if (contant.split("哈")[1] == "顺子") {
                            peilv = conf.peilv['shunzi'];
                            xiazhujinearray[11] += amount
                        }
                        if (contant.split("哈")[1] == "豹子") {
                            peilv = conf.peilv['baozi'];
                            baozi_xiazhujine = parseInt(amount)
                        }
                        if (contant.split("哈")[1] == "对子") {
                            peilv = conf.peilv['duizi'];
                            xiazhujinearray[12] += amount
                        }
                        if (contant.split("哈")[1] == "极大") {
                            peilv = conf.peilv['jizhi'];
                            xiazhujinearray[8] += amount
                        }
                        if (contant.split("哈")[1] == "极小") {
                            peilv = conf.peilv['jizhi'];
                            xiazhujinearray[9] += amount
                        }
                        /*if (contant.split("哈")[1] == "合") {
                            peilv = conf.peilv['he'];
                            xiazhujinearray[10] += amount
                        }*/


                        if (guess == "" || peilv == 0) {
                            connection.destroy();
                            return;
                        }

                        if (userBalance <= 0) {
                            bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();
                            return;
                        }
                        if (amount > conf.betMax || amount < conf.betMin) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限，最大下注金额为${conf.betMax}</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();
                            return;
                        }
                        connection.query(`select sum(amount)
                                          FROM pc_bet
                                          where type = '${conf.type}'
                                            and resultid = "${resultid}"
                                            and guess like "豹%"
                                            and telegramid = "${telegramid}";
                        select sum(amount)
                        FROM pc_bet
                        where type = '${conf.type}'
                          and resultid = "${resultid}"
                          and guess = "豹子"
                          and telegramid = "${telegramid}";
                        select sum(amount)
                        FROM pc_bet
                        where type = '${conf.type}'
                          and resultid = "${resultid}"
                          and telegramid = "${telegramid}";`, (error, result) => {
                            if (error) return error;
                            if ((result[0][0]['sum(amount)'] ? parseFloat(result[0][0]['sum(amount)']) : 0) + shabaozi_xiazhujine > conf.xianzhu.dianshabaozi) {
                                bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                    reply_to_message_id: replyMessageid,
                                    parse_mode: "HTML"
                                })
                                connection.destroy();
                                return
                            }
                            if ((result[1][0]['sum(amount)'] ? parseFloat(result[1][0]['sum(amount)']) : 0) + baozi_xiazhujine > conf.xianzhu.baozi) {
                                bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                    reply_to_message_id: replyMessageid,
                                    parse_mode: "HTML"
                                })
                                connection.destroy();
                                return
                            }
                            console.log('cosnole1=========================================');
                            /*if ((result[2][0]['sum(amount)']?parseFloat(result[2][0]['sum(amount)']):0)+xiazhujine>conf.betMax) {
                                bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                    reply_to_message_id: replyMessageid,
                                    parse_mode:"HTML"
                                })
                                connection.destroy();

                            return
                        }*/
                            connection.query(`select sum(amount)
                                              FROM pc_bet
                                              where type = '${conf.type}'
                                                and guess = "大"
                                                and telegramid = "${telegramid}"
                                                and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "小"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "单"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "双"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "大单"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "小单"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "大双"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "小双"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "龙"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "虎"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "合"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "顺子"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";
                            select sum(amount)
                            FROM pc_bet
                            where type = '${conf.type}'
                              and guess = "对子"
                              and telegramid = "${telegramid}"
                              and resultid = "${resultid}";`, (error, result) => {
                                if (error) return error;
                                for (let index = 0; index < result.length; index++) {
                                    if (parseFloat(result[index][0]['sum(amount)']) + parseFloat(xiazhujinearray[index]) > conf.xianzhu.qita) {
                                        connection.destroy();
                                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                            reply_to_message_id: replyMessageid,
                                            parse_mode: "HTML"
                                        })
                                        return;
                                    }
                                }
                                console.log('cosnole2=========================================');
                                connection.query(`select *
                                                  from users
                                                  where telegramid = "${telegramid}";`, (error, userresult) => {
                                    if (error) return error;
                                    if (userresult[0].balance <= 0) {
                                        bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`, {
                                            reply_to_message_id: replyMessageid,
                                            parse_mode: "HTML"
                                        })
                                        connection.destroy();
                                        return;
                                    }
                                    amount = userresult[0].balance;
                                    console.log('梭哈插入bet表，resultid为====', resultid)
                                    console.log('梭哈插入bet表，amount为====', amount)
                                    connection.query(`insert into pc_bet (telegramid, name, amount, guess, time,
                                                                          resultid,
                                                                          messageid, firstname, peilv,
                                                                          inviter_telegramid, type)
                                                      VALUES ("${telegramid}", "${name}", ${amount}, "${guess}", now(),
                                                              "${resultid}", "${replyMessageid}",
                                                              "${utf16toEntities(firstname)}", "${peilv}",
                                                              "${userinfo.inviter_telegramid}", "${conf.type}");
                                    UPDATE users
                                    set balance = balance - ${amount}
                                    where telegramid = ${telegramid};`, (error, result) => {
                                        console.log('cosnole3=========================================')
                                        console.log(error)
                                        if (error) return error;
                                        connection.query(`select *
                                                          from users
                                                          where telegramid = "${telegramid}";
                                        select *
                                        FROM pc_bet
                                        where type = '${conf.type}'
                                          and telegramid = ${telegramid}
                                          and resultid = '${resultid}'
                                        ORDER BY id DESC;`, (error, result) => {
                                            connection.destroy();
                                            console.log(error)
                                            console.log('下注之后查询下注表返回========', result[1])
                                            if (error) throw error;
                                            var quanbutouzhu = "";
                                            for (var index = 0; index < result[1].length; index++) {
                                                quanbutouzhu += `<code>${result[1][index].guess}</code>-<code>${result[1][index].amount}</code>(${result[1][index].peilv}倍赔率)\n`
                                            }


                                            let returnMsg = `<b>第${resultid}期</b> \n✅成功 \n ${contant} (${result[1][0].peilv}倍赔率) \n--------- \n余额：${(result[0][0].balance)}元 \n---------`
                                            bot.sendMessage(conf.chatid, returnMsg, {
                                                reply_to_message_id: replyMessageid,
                                                parse_mode: "HTML",
                                                reply_markup: {
                                                    inline_keyboard: conf.xiazhu_inline_keyboard
                                                },
                                            })
                                        });
                                    });
                                });

                            });

                        });
                    }


                } else {
                    console.log('cosnole4=========================================');
                    const contantArray = contant.split(/\s+/);
                    var allbet = "", amount, guess = "", peilv = "",
                        sql = "insert into pc_bet (telegramid ,name ,amount ,guess ,time ,resultid,messageid,firstname,peilv,inviter_telegramid,type) VALUES";
                    for (let index = 0; index < contantArray.length; index++) {
                        amount = 0, guess = "";
                        if (contantArray[index].search("大单") != -1 && contantArray[index].split("大单").length == 2) {
                            if (contantArray[index].split("大单")[0] == "") {
                                amount = contantArray[index].split("大单")[1];
                            } else {
                                amount = contantArray[index].split("大单")[0];
                            }
                            guess = "大单";
                            peilv = conf.peilv['fushi1'];
                            xiazhujinearray[4] += parseInt(amount)
                        } else {
                            if (contantArray[index].search("大") != -1 && contantArray[index].split("大").length == 2) {

                                if (contantArray[index].split("大")[0] == "") {
                                    amount = contantArray[index].split("大")[1];
                                } else {
                                    amount = contantArray[index].split("大")[0];
                                }
                                guess = "大";
                                peilv = conf.peilv['dxds'];
                                xiazhujinearray[0] += parseInt(amount)
                            }
                            if (contantArray[index].search("单") != -1 && contantArray[index].split("单").length == 2) {
                                if (contantArray[index].split("单")[0] == "") {
                                    amount = contantArray[index].split("单")[1];
                                } else {
                                    amount = contantArray[index].split("单")[0];
                                }
                                guess = "单";
                                peilv = conf.peilv['dxds'];
                                xiazhujinearray[2] += parseInt(amount)
                            }
                        }

                        if (contantArray[index].search("小双") != -1 && contantArray[index].split("小双").length == 2) {
                            if (contantArray[index].split("小双")[0] == "") {
                                amount = contantArray[index].split("小双")[1];
                            } else {
                                amount = contantArray[index].split("小双")[0];
                            }
                            guess = "小双";
                            peilv = conf.peilv['fushi1'];
                            xiazhujinearray[7] += parseInt(amount)
                        } else {
                            if (contantArray[index].search("小") != -1 && contantArray[index].split("小").length == 2) {
                                if (contantArray[index].split("小")[0] == "") {
                                    amount = contantArray[index].split("小")[1];
                                } else {
                                    amount = contantArray[index].split("小")[0];
                                }
                                guess = "小";
                                peilv = conf.peilv['dxds'];
                                xiazhujinearray[1] += parseInt(amount)
                            }
                            if (contantArray[index].search("双") != -1 && contantArray[index].split("双").length == 2) {
                                if (contantArray[index].split("双")[0] == "") {
                                    amount = contantArray[index].split("双")[1];
                                } else {
                                    amount = contantArray[index].split("双")[0];
                                }
                                guess = "双";
                                peilv = conf.peilv['dxds'];
                                xiazhujinearray[3] += parseInt(amount)
                            }
                        }

                        if (contantArray[index].search("大双") != -1 && contantArray[index].split("大双").length == 2) {
                            if (contantArray[index].split("大双")[0] == "") {
                                amount = contantArray[index].split("大双")[1];
                            } else {
                                amount = contantArray[index].split("大双")[0];
                            }
                            guess = "大双";
                            peilv = conf.peilv['fushi2'];
                            xiazhujinearray[6] += parseInt(amount)
                        }

                        if (contantArray[index].search("小单") != -1 && contantArray[index].split("小单").length == 2) {
                            if (contantArray[index].split("小单")[0] == "") {
                                amount = contantArray[index].split("小单")[1];
                            } else {
                                amount = contantArray[index].split("小单")[0];
                            }
                            guess = "小单";
                            peilv = conf.peilv['fushi2'];
                            xiazhujinearray[5] += parseInt(amount)
                        }

                        if (contantArray[index].search("豹子") != -1 && contantArray[index].split("豹子").length == 2) {
                            if (contantArray[index].split("豹子")[0] == "") {
                                amount = contantArray[index].split("豹子")[1];
                            } else {
                                amount = contantArray[index].split("豹子")[0];
                            }
                            guess = "豹子";
                            peilv = conf.peilv['baozi'];
                            baozi_xiazhujine += parseInt(amount)
                        }
                        if (contantArray[index].search("顺子") != -1 && contantArray[index].split("顺子").length == 2) {
                            if (contantArray[index].split("顺子")[0] == "") {
                                amount = contantArray[index].split("顺子")[1];
                            } else {
                                amount = contantArray[index].split("顺子")[0];
                            }
                            guess = "顺子";
                            peilv = conf.peilv['shunzi'];
                            xiazhujinearray[11] += parseInt(amount)
                        }
                        if (contantArray[index].search("对子") != -1 && contantArray[index].split("对子").length == 2) {
                            if (contantArray[index].split("对子")[0] == "") {
                                amount = contantArray[index].split("对子")[1];
                            } else {
                                amount = contantArray[index].split("对子")[0];
                            }
                            guess = "对子";
                            peilv = conf.peilv['duizi'];
                            xiazhujinearray[12] += parseInt(amount)
                        }

                        if (contantArray[index].search("极大") != -1 && contantArray[index].split("极大").length == 2) {
                            if (contantArray[index].split("极大")[0] == "") {
                                amount = contantArray[index].split("极大")[1];
                            } else {
                                amount = contantArray[index].split("极大")[0];
                            }
                            guess = "极大";
                            peilv = conf.peilv['jizhi'];
                            xiazhujinearray[8] += parseInt(amount)
                        }

                        if (contantArray[index].search("极小") != -1 && contantArray[index].split("极小").length == 2) {
                            if (contantArray[index].split("极小")[0] == "") {
                                amount = contantArray[index].split("极小")[1];
                            } else {
                                amount = contantArray[index].split("极小")[0];
                            }
                            guess = "极小";
                            peilv = conf.peilv['jizhi'];
                            xiazhujinearray[9] += parseInt(amount)
                        }

                        /*if (contantArray[index].search("合") != -1 && contantArray[index].split("合").length == 2) {
                            if (contantArray[index].split("合")[0] == "") {
                                amount = contantArray[index].split("合")[1];
                            } else {
                                amount = contantArray[index].split("合")[0];
                            }
                            guess = "合";
                            peilv = conf.peilv['he'];
                            xiazhuji
                            nearray[10] += parseInt(amount)
                        }*/


                        if (contantArray[index].search("押") != -1) {
                            if (contantArray[index].split("押")[0] == "1" || contantArray[index].split("押")[0] == "2" || contantArray[index].split("押")[0] == "3" || contantArray[index].split("押")[0] == "4" || contantArray[index].split("押")[0] == "5" || contantArray[index].split("押")[0] == "6" || contantArray[index].split("押")[0] == "7" || contantArray[index].split("押")[0] == "8" || contantArray[index].split("押")[0] == "9" || contantArray[index].split("押")[0] == "10" || contantArray[index].split("押")[0] == "11" || contantArray[index].split("押")[0] == "12" || contantArray[index].split("押")[0] == "13" || contantArray[index].split("押")[0] == "14" || contantArray[index].split("押")[0] == "15" || contantArray[index].split("押")[0] == "16" || contantArray[index].split("押")[0] == "17" || contantArray[index].split("押")[0] == "18" || contantArray[index].split("押")[0] == "19" || contantArray[index].split("押")[0] == "20" || contantArray[index].split("押")[0] == "21" || contantArray[index].split("押")[0] == "22" || contantArray[index].split("押")[0] == "23" || contantArray[index].split("押")[0] == "24" || contantArray[index].split("押")[0] == "25" || contantArray[index].split("押")[0] == "26" || contantArray[index].split("押")[0] == "27") {
                                if (typeof parseFloat(contantArray[index].split("押")[1]) === 'number' && !isNaN(contantArray[index].split("押")[1])) {
                                    amount = contantArray[index].split("押")[1];
                                    guess = "押" + contantArray[index].split("押")[0] + "点";
                                    peilv = conf.peilv['s' + contantArray[index].split("押")[0] + 'd'];
                                    shuzi_xiazhujine += parseInt(amount)
                                    if (shuziamount[guess] + parseFloat(amount) > conf.xianzhu.danshuzi) {
                                        let returnMsg = `<b>第${resultid}期</b> \n ✅成功 \n ${contant} \n--------- \n余额：${(result[0][0].balance)}元  \n---------`
                                        bot.sendMessage(conf.chatid, returnMsg, {
                                            reply_to_message_id: replyMessageid,
                                            parse_mode: "HTML"
                                        })
                                        connection.destroy();
                                        return;
                                    }
                                }
                            }
                        }

                        if (contantArray[index].search("T") != -1) {
                            if (contantArray[index].split("T")[0] == "4" || contantArray[index].split("T")[0] == "5" || contantArray[index].split("T")[0] == "6" || contantArray[index].split("T")[0] == "7" || contantArray[index].split("T")[0] == "8" || contantArray[index].split("T")[0] == "9" || contantArray[index].split("T")[0] == "10" || contantArray[index].split("T")[0] == "11" || contantArray[index].split("T")[0] == "12" || contantArray[index].split("T")[0] == "13" || contantArray[index].split("T")[0] == "14" || contantArray[index].split("T")[0] == "15" || contantArray[index].split("T")[0] == "16" || contantArray[index].split("T")[0] == "17") {
                                if (typeof parseFloat(contantArray[index].split("T")[1]) === 'number' && !isNaN(contantArray[index].split("T")[1])) {
                                    amount = contantArray[index].split("T")[1];
                                    guess = "押" + contantArray[index].split("T")[0] + "点";
                                    peilv = conf.peilv['s' + contantArray[index].split("T")[0] + 'd'];
                                    shuzi_xiazhujine += parseInt(amount)
                                    if (shuziamount[guess] + parseFloat(amount) > conf.xianzhu.danshuzi) {
                                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                            reply_to_message_id: replyMessageid,
                                            parse_mode: "HTML"
                                        })
                                        connection.destroy();
                                        return;
                                    }
                                }
                            }
                        }

                        if (contantArray[index].search("豹子") != -1) {
                            if (contantArray[index].split("豹子")[0] == "1" || contantArray[index].split("豹子")[0] == "2" || contantArray[index].split("豹子")[0] == "3" || contantArray[index].split("豹子")[0] == "4" || contantArray[index].split("豹子")[0] == "5" || contantArray[index].split("豹子")[0] == "6") {
                                if (parseFloat(contantArray[index].split("豹子")[1]) % 1 == 0 && !isNaN(contantArray[index].split("豹子")[1])) {
                                    amount = contantArray[index].split("豹子")[1];
                                    guess = "豹子" + contantArray[index].split("豹子")[0] + "点";
                                    peilv = conf.peilv['dsbz'];
                                    shabaozi_xiazhujine += parseInt(amount)
                                }
                            }
                        }

                        console.log('console7=========================================');
                        xiazhujine += parseInt(amount);
                        if (index == 0) {
                            sql = sql + ` ("${telegramid}","${name}",${amount},"${guess}",now(),"${resultid}","${replyMessageid}","${utf16toEntities(firstname)}",${peilv},"${userinfo.inviter_telegramid}","${conf.type}")`;
                        } else {
                            sql = sql + ` ,("${telegramid}","${name}",${amount},"${guess}",now(),"${resultid}","${replyMessageid}","${utf16toEntities(firstname)}",${peilv},"${userinfo.inviter_telegramid}","${conf.type}")`;
                        }

                        allbet = allbet + `✅${guess}-${amount}\n`

                        if (amount == "" || /[\u4e00-\u9fa5]+/.test(amount) || /[a-zA-Z]+/.test(amount) || amount % 1 != 0) {
                            connection.destroy();
                            return;
                        }
                        if (amount <= 0 || guess == "") {
                            connection.destroy();
                            return;
                        }

                        if (amount > conf.betMax || amount < conf.betMin) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限，最大下注金额为${conf.betMax}</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();
                            return;
                        }

                    }

                    if (isfengpan) {
                        bot.sendMessage(conf.chatid, `<b>❌慢！本期已封盘 , 投注无效！</b>`, {
                            reply_to_message_id: replyMessageid,
                            parse_mode: "HTML"
                        })
                        connection.destroy();
                        return;
                    }

                    if (userBalance < xiazhujine) {
                        bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`, {
                            reply_to_message_id: replyMessageid,
                            parse_mode: "HTML"
                        })
                        connection.destroy();
                        return;
                    }
                    console.log('cosnole8=========================================');
                    connection.query(`select sum(amount)
                                      FROM pc_bet
                                      where type = '${conf.type}'
                                        and resultid = "${resultid}"
                                        and guess like "豹%"
                                        and telegramid = "${telegramid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and resultid = "${resultid}"
                      and guess = "豹子"
                      and telegramid = "${telegramid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and resultid = "${resultid}"
                      and telegramid = "${telegramid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and resultid = "${resultid}"
                      and guess like "押%"
                      and telegramid = "${telegramid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "大"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "小"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "单"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "双"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "大单"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "小单"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "大双"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "小双"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "龙"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "虎"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "合"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "顺子"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";
                    select sum(amount)
                    FROM pc_bet
                    where type = '${conf.type}'
                      and guess = "对子"
                      and telegramid = "${telegramid}"
                      and resultid = "${resultid}";`, (error, result) => {
                        console.log(error)
                        if (error) return error;
                        if ((result[0][0]['sum(amount)'] ? parseFloat(result[0][0]['sum(amount)']) : 0) + shabaozi_xiazhujine > conf.xianzhu.dianshabaozi) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();
                            return
                        }
                        if ((result[1][0]['sum(amount)'] ? parseFloat(result[1][0]['sum(amount)']) : 0) + baozi_xiazhujine > conf.xianzhu.baozi) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();
                            return
                        }
                        if ((result[2][0]['sum(amount)'] ? parseFloat(result[2][0]['sum(amount)']) : 0) + xiazhujine > conf.danqibetMax) {
                            let returnMsg = `<b>第${resultid}期</b> \n✅成功 \n ${contant} \n--------- \n余额：${(result[0][0].balance)}元 \n---------`
                            bot.sendMessage(conf.chatid, returnMsg, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();

                            return
                        }
                        if ((result[3][0]['sum(amount)'] ? parseFloat(result[3][0]['sum(amount)']) : 0) + shuzi_xiazhujine > conf.xianzhu.zongshuzi) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                reply_to_message_id: replyMessageid,
                                parse_mode: "HTML"
                            })
                            connection.destroy();

                            return
                        }
                        console.log('cosnole9=========================================');
                        for (let index = 4; index < result.length - 4; index++) {

                            if (parseFloat(result[index][0]['sum(amount)']) + parseFloat(xiazhujinearray[index - 4]) > conf.xianzhu.qita) {
                                connection.destroy();
                                bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`, {
                                    reply_to_message_id: replyMessageid,
                                    parse_mode: "HTML"
                                })
                                return;
                            }
                        }

                        connection.query(`select *
                                          from users
                                          where telegramid = "${telegramid}";`, (error, result) => {
                            if (error) return error;
                            if (result[0].balance < xiazhujine) {
                                bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`, {
                                    reply_to_message_id: replyMessageid,
                                    parse_mode: "HTML"
                                })
                                connection.destroy();
                                return;
                            }
                            console.log('cosnole10=========================================');
                            connection.query(`${sql};UPDATE users set balance = balance - ${xiazhujine}  where telegramid = "${telegramid}";${isnertresultsql}`, (error, result) => {
                                console.log(error)
                                if (error) return error;
                                connection.query(`select *
                                                  from users
                                                  where telegramid = "${telegramid}";
                                select *
                                FROM pc_bet
                                where type = '${conf.type}'
                                  and telegramid = ${telegramid}
                                  and resultid = '${resultid}'
                                ORDER BY time DESC;`, (error, result) => {
                                    connection.destroy();
                                    console.log(error)
                                    console.log('==============================', `select *
                                                                                   FROM pc_bet
                                                                                   where type = '${conf.type}'
                                                                                     and telegramid = ${telegramid}
                                                                                     and resultid = '${resultid}'`)
                                    if (error) return error;
                                    var quanbutouzhu = "";
                                    for (var index = 0; index < result[1].length; index++) {
                                        quanbutouzhu += `${result[1][index].guess}-${result[1][index].amount}元赔率：${result[1][index].peilv}倍\n`
                                    }

                                    let returnMsg = `<b>第${resultid}期</b> \n ✅成功 \n ${contant} (${result[1][0].peilv}倍赔率) \n--------- \n余额：${(result[0][0].balance)}元 \n---------`

                                    bot.sendMessage(conf.chatid, returnMsg, {
                                        reply_to_message_id: replyMessageid,
                                        parse_mode: "HTML",
                                        reply_markup: {
                                            inline_keyboard: conf.xiazhu_inline_keyboard
                                        },
                                    })

                                });
                            });
                        });
                    });
                }

            });
    })
}


/*查询流水*/
function getTodayBill(telegramid, name, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = "${telegramid}";
        select *
        FROM pc_bet
        where type = '${conf.type}'
          and telegramid = "${telegramid}"
          and resultid = '${resultid}';`, (error, result) => {
            connection.destroy();
            if (error) return error;
            if (result[0].length == 0) {

            } else {
                var quanbutouzhu = "";
                for (var index = 0; index < result[1].length; index++) {
                    quanbutouzhu += `${result[1][index].guess}-${result[1][index].amount}(${result[1][index].peilv}倍赔率)\n`
                }
                bot.answerCallbackQuery(callbackQueryid, {
                    text: `${resultid}期全部投注：\n${quanbutouzhu}`,
                    show_alert: true,
                    cache_time: 10
                })
            }
        });

    });
}

function tongji(telegramid, name, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where telegramid = "${telegramid}";
        SELECT sum(amount), sum(result), sum(amountreturn)
        FROM pc_bet
        where type = '${conf.type}'
          and telegramid = "${telegramid}"
          and time like "${moment(Math.round(date) - 1000 * 60 * 60 * 24).format("YYYY-MM-DD")}%";`, (error, result) => {
            connection.destroy();
            if (error) return error;
            if (!result[0][0]) {
                return
            }
            bot.answerCallbackQuery(callbackQueryid, {
                text: `昨日数据详情\n投注:${(result[1][0]['sum(amount)'] ? result[1][0]['sum(amount)'] : 0)}  盈利:${parseInt(result[1][0]['sum(result)'] - result[1][0]['sum(amount)'] + result[1][0]['sum(amountreturn)'] + result[1][0]['sum(amount)'] * 0.01)}\n反水:${parseInt(result[1][0]['sum(amountreturn)'] + result[1][0]['sum(amount)'] * 0.01)}  回水:${parseInt(result[0][0]['huishui'])}`,
                show_alert: true,
                cache_time: 1
            })
                .catch(e => {
                    console.log("领取反水出错");
                })
        });
    });
}

function huiWaterHandler() {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users`, (err, result) => {
            if (err) return err;
            if (result[0]) {
                result[0].forEach(item => {
                    getHuiWater(item.telegramid)
                })
            }
            connection.destroy();
        })
    });
};

/*领取回水*/
function getHuiWater(telegramid, name, callbackQueryid) {

    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT SUM(amount)
                          FROM pay
                          where telegramid = "${telegramid}"
                            and state = 1
                            and applytime like "${moment(Math.round(date) - 1000 * 60 * 60 * 24).format("YYYY-MM-DD")}%";
        SELECT SUM(amount)
        FROM withdrawal
        where telegramid = "${telegramid}"
          and state = 1
          and applytime like "${moment(Math.round(date) - 1000 * 60 * 60 * 24).format("YYYY-MM-DD")}%";
        SELECT *
        FROM users
        where telegramid = "${telegramid}";`, (error, result) => {
            if (error) return error;
            if (!result[2][0]) {
                /*bot.answerCallbackQuery(callbackQueryid, {
                    text: `领取回水：0 ${conf.coin}`,
                    show_alert: true,
                    cache_time: 1
                })*/
                connection.destroy();
                return
            }
            var shuying = -(result[0][0]['SUM(amount)'] ? result[0][0]['SUM(amount)'] : 0) + (result[1][0]['SUM(amount)'] ? result[1][0]['SUM(amount)'] : 0) + result[2][0].balance;
            var huishui = 0
            if (shuying < (result[0][0]['SUM(amount)'] ? result[0][0]['SUM(amount)'] : 0) * 0.05) {
                huishui = (((result[0][0]['SUM(amount)'] ? result[0][0]['SUM(amount)'] : 0) - (result[1][0]['SUM(amount)'] ? result[1][0]['SUM(amount)'] : 0)) * 0.03)
            }
            if (result[2][0].lasthuishui == moment().format("YYYY-MM-DD")) {
                connection.destroy();
                /*bot.answerCallbackQuery(callbackQueryid, {
                    text: `您已领取今日回水`,
                    show_alert: true,
                    cache_time: 1
                })
                    .catch(e => {
                        console.log("领取回水出错");
                    })*/
            } else {
                connection.query(`UPDATE users
                                  set balance           = balance + ${huishui},
                                      huishui           = huishui + ${huishui},
                                      lasthuishu_amount = ${huishui},
                                      lasthuishui       = "${moment().format("YYYY-MM-DD")}"
                                  where telegramid = "${telegramid}";`, (error, result) => {
                    connection.destroy();
                    if (error) return error;
                    /*bot.answerCallbackQuery(callbackQueryid, {
                        text: `领取回水：${huishui} ${conf.coin}`,
                        show_alert: true,
                        cache_time: 1
                    })
                        .catch(e => {
                            console.log("领取回水出错");
                        })*/
                });
            }

        });
    });
}

/*领取反水*/
function getReturnWater(telegramid, name, callbackQueryid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pay
                          where telegramid = "${telegramid}"
                            and state = 1
                          order by id desc limit 3;
        SELECT *
        FROM withdrawal
        where telegramid = "${telegramid}"
          and state = 1
        order by id desc limit 3;`, (error, result) => {
            connection.destroy();
            if (error) return error;
            var chongzhi = "充值:\n";
            var tixian = "提现:\n"
            for (let index = 0; index < result[0].length; index++) {
                chongzhi = `${chongzhi}【${result[0][index].applytime.split("2023-")[1].substring(result[0][index].applytime.split("2023-")[1].length - 3, result[0][index].applytime.split("2023-")[1])}】${result[0][index].amount}${conf.coin}\n`;
            }
            for (let index = 0; index < result[1].length; index++) {
                tixian = `${tixian}【${result[1][index].applytime.split("2023-")[1].substring(result[1][index].applytime.split("2023-")[1].length - 3, result[1][index].applytime.split("2023-")[1])}】${result[1][index].amount}${conf.coin}\n`;
            }
            if (error) return error;
            bot.answerCallbackQuery(callbackQueryid, {
                text: `${(chongzhi == "提现" ? "" : chongzhi)}\n${(tixian == "提现" ? "" : tixian)}`,
                show_alert: true,
                cache_time: 1
            })
                .catch(e => {
                    console.log("领取反水出错");
                })
        });
    });
}

/*开奖*/
function setResult() {
    let resultid = resultArr[0].qishu
    console.log('开奖===========resultid', resultid)
    conf.pool.getConnection(function (err, connection) {
        console.log('err===', err)
        if (err) return err;
        connection.query(`SELECT *
                          FROM pc_bet
                          where type = '${conf.type}'
                            and resultid = "${resultid}"
                            and result is null
                          order by id desc;
        SELECT *
        FROM pc_result
        where type = '${conf.type}'
          and id = "${resultid}" `, (error, resultRoot) => {


            let result1 = resultRoot[1]
            let result = resultRoot[0]
            console.log('setResultroot=====', resultRoot)
            console.log('setResult0=====', result)
            console.log('setResult1=====', result1)

            a = result1[0].one;
            b = result1[0].two;
            c = result1[0].three;
            // resultid = parseInt(result[0].resultid);

            value = a + b + c;
            /*初始化*/
            resultdxds = {
                big: 0,
                small: 0,
                odd: 0,
                even: 0,
                baozi: 0,
                shunzi: 0,
                duizi: 0,
                jida: 0,
                jixiao: 0,
            };
            baozi = "";
            shunzi = "";
            duizi = "";
            daxiao = "";
            danshuang = "";
            jizhi = "";


            if (c - b == 1 && b - a == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }
            if (c - a == 1 && b - c == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }
            if (a - b == 1 && c - a == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }
            if (b - a == 1 && a - c == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }
            if (a - b == 1 && b - c == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }
            if (a - c == 1 && c - b == 1) {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }

            // 开出890/190等三个数字均为顺子
            let abcStr = '' + a + b + c
            if (abcStr === '890' || abcStr === '809' || abcStr === '980' || abcStr === '908' || abcStr === '089' || abcStr === '098' ||
                abcStr === '190' || abcStr === '109' || abcStr === '019' || abcStr === '091' || abcStr === '910' || abcStr === '901') {
                resultdxds.shunzi = 1;
                shunzi = "顺子";
            }


            if (a == b && b != c) {
                resultdxds.duizi = 1;
                duizi = "对子";
            }
            if (b == c && c != a) {
                resultdxds.duizi = 1;
                duizi = "对子";
            }
            if (a == c && c != b) {
                resultdxds.duizi = 1;
                duizi = "对子";
            }

            if (a == b && b == c && c == a) { //如果是豹，通杀
                resultdxds.baozi = 1;
                baozi = "豹子";
            }

            console.log('a+b+c的和========', value)
            /*大小*/
            if (value >= 14 && value <= 27) {
                resultdxds.big = 1;
                daxiao = "大";
            }
            if (value >= 0 && value <= 13) {
                resultdxds.small = 1;
                daxiao = "小";
            }
            /*单双*/
            if (value % 2 == 1) {
                resultdxds.odd = 1;
                danshuang = "单";
            }
            if (value % 2 == 0 || value == 0) {
                resultdxds.even = 1;
                danshuang = "双";
            }

            // 极小
            if (value >= 0 && value <= 5) {
                resultdxds.jixiao = 1;
                jizhi = "极小"
            }

            // 极大
            if (value >= 22 && value <= 27) {
                resultdxds.jida = 1;
                jizhi = "极大"
            }


            console.log('result[0]=====', result);
            if (result && result.length === 0) {
                console.log('没有人下注！==========')
                let history = ''
                connection.query(`update pc_result
                                  set big    = ${resultdxds.big},
                                      small  = ${resultdxds.small},
                                      odd    = ${resultdxds.odd},
                                      even   = ${resultdxds.even},
                                      baozi  = ${resultdxds.baozi},
                                      shunzi = ${resultdxds.shunzi},
                                      duizi  = ${resultdxds.duizi},
                                      jida   = "${resultdxds.jida}",
                                      jixiao = "${resultdxds.jixiao}"
                                  where id = "${resultid}";`, (error, result) => {
                    connection.query(`SELECT *
                                      FROM pc_result
                                      WHERE type = '${conf.type}'
                                        and one is not null
                                        and two is not null
                                        and three is not null
                                      ORDER BY id DESC LIMIT 10;`, (error, result) => {
                        console.log(error)
                        if (error) return error;
                        if (result) {
                            result.forEach(item => {
                                history += `${item.id}期 <code>${item.one} ${item.two} ${item.three} = ${item.one + item.two + item.three} ${item.big == 1 ? "大" : ""}${item.small == 1 ? "小" : ""}${item.odd == 1 ? "单" : ""}${item.even == 1 ? "双" : ""}${item.baozi == 1 ? " 豹子" : ""}${item.shunzi == 1 ? " 顺子" : ""}${item.duizi == 1 ? " 对子" : ""}${item.jida == 1 ? " 极大" : ""}${item.jixiao == 1 ? " 极小" : ""}</code>  \n`
                            });
                        }
                        let numA = Number.parseInt(a);
                        let numB = Number.parseInt(b);
                        let numC = Number.parseInt(c);
                        var sendruselttxt = `<code>${resultid}期</code>开奖结果\n${a}+${b}+${c}=${numA + numB + numC}  结果-${daxiao} ${danshuang} ${baozi} ${shunzi} ${duizi} ${jizhi}\n\n恒旺集团娱乐🐲\n每日充值送10%彩金/负盈利反水%5\n充值地址:\nTWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd \n ———————————————————— \n 🧧㊗️老板们多多盈利，美金越来越多💵💵💵🧧\n🎉手气爆棚 天天提款🧨🧨🧨\n🎉财源广进  天天嫩模 🧨🧨🧨\n\n👍 公平 公正 公开 \n👍💎月入百万不是梦💎\n💎看你心动不行动💎 \n \n <code>------历史开奖走势------</code> \n${history}`;

                        bot.sendMessage(conf.chatid, sendruselttxt, {
                            parse_mode: "HTML",
                            disable_web_page_preview: true,
                            reply_markup: JSON.stringify({
                                inline_keyboard: conf.guize_inline_keyboard
                            })
                        })
                        connection.query(`update pc_result
                                          SET result_time = now()
                                          WHERE id = ${resultid}
                                            AND type = ${conf.type};`, (error, result) => {
                            console.log(error)
                            if (error) return error;
                            connection.destroy()
                        })

                    })
                });

                // 历史开奖
                return;
            }

            if (result[0]) {
                resultArray = result;
                connection.query(`update pc_result
                                  set big    = ${resultdxds.big},
                                      small  = ${resultdxds.small},
                                      odd    = ${resultdxds.odd},
                                      even   = ${resultdxds.even},
                                      baozi  = ${resultdxds.baozi},
                                      shunzi = ${resultdxds.shunzi},
                                      duizi  = ${resultdxds.duizi},
                                      jida   = "${resultdxds.jida}",
                                      jixiao = "${resultdxds.jixiao}"
                                  where id = "${resultid}";`, (error, result) => {

                    var allResultMessage = "";
                    var winResultMessage = "🎉🎉恭喜中奖玩家🎉🎉\n\n";
                    var allResultSql = "";
                    var invitesql = "";
                    for (let index = 0; index < resultArray.length; index++) {
                        if (parseInt(resultArray[index].inviter_telegramid) % 1 == 0) {
                            invitesql += `update users
                                          set yongjinbalance = yongjinbalance + ${resultArray[index].amount * conf.yongjin},
                                              zhouyongjin    = zhouyongjin + ${resultArray[index].amount * conf.yongjin}
                                          where telegramid = "${resultArray[index].inviter_telegramid}";
                            insert into jiangli (telegramid, amount, type, time)
                            values ("${resultArray[index].inviter_telegramid}",
                                    ${resultArray[index].amount * conf.yongjin},
                                    "下级${resultArray[index].telegramid}快三佣金奖励", now());`;
                        }
                    }
                    for (let index = 0; index < resultArray.length; index++) {
                        var allResult = resultArray[index];
                        console.log('allResult====', allResult)
                        if (value == 13 || value == 14) {
                            // 13和14直接回本
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}
                            update pc_bet
                            set result = 0
                            where id = ${allResult.id};
                            update users
                            set lastbet_time = now(),
                                balance      = balance + ${allResult.amount}
                            where telegramid = "${allResult.telegramid}";`
                        } else {
                            if (allResult.guess == "大" || allResult.guess == "小" || allResult.guess == "单" || allResult.guess == "双") {
                                if (allResult.guess == daxiao || allResult.guess == danshuang) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${2.8 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(2.8 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(2.8 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "大单") {
                                if (value == 15 || value == 17 || value == 19 || value == 21 || value == 23 || value == 25 || value == 27) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${6 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(6 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(6 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "小双") {
                                if (value == 0 || value == 2 || value == 4 || value == 6 || value == 8 || value == 10 || value == 12) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${6 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(6 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(6 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "大双") {
                                if (value == 14 || value == 16 || value == 18 || value == 20 || value == 22 || value == 24 || value == 26) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${6 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(6 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(6 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }
                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "小单") {
                                if (value == 1 || value == 3 || value == 5 || value == 7 || value == 9 || value == 11 || value == 13) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${6 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(6 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(6 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }


                            if (allResult.guess == "豹子") {
                                if (resultdxds.baozi == 1) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${1.7 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(1.7 * allResult.amount - allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    // 豹子没有猜中的，回本
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        balance      = balance + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "顺子") {
                                if (resultdxds.shunzi == 1) {
                                    allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                    winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = ${allResult.peilv * allResult.amount}
                                    where id = ${allResult.id};
                                    update users
                                    set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                        todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount},
                                        lastbet_time = now()
                                    where telegramid = "${allResult.telegramid}";`
                                } else {
                                    // 没有猜中，回本
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        balance      = balance + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                            if (allResult.guess == "对子") {
                                if (resultdxds.duizi == 1) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${1.7 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(1.7 * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }

                                } else {
                                    // 对子没有猜中，回本
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        balance      = balance + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }

                            if (allResult.guess.search("押") != -1 && allResult.guess.search("点") != -1) {
                                if (parseInt(allResult.guess.split("点")[0].split("押")[1]) == value) {
                                    if (false) {
                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${1.7 * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(1.7 * allResult.amount - allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    } else {
                                        allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                        allResultSql = `${allResultSql}
                                        update pc_bet
                                        set result = ${allResult.peilv * allResult.amount}
                                        where id = ${allResult.id};
                                        update users
                                        set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                            todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                            liushui      = liushui + ${allResult.amount},
                                            zongliushui  = zongliushui + ${allResult.amount},
                                            lastbet_time = now()
                                        where telegramid = "${allResult.telegramid}";`
                                    }
                                } else {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = 0
                                    where id = ${allResult.id};
                                    update users
                                    set lastbet_time = now(),
                                        todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount}
                                    where telegramid = "${allResult.telegramid}";`
                                }
                            }
                        }

                        /*if (allResult.guess.search("豹子") != -1 && allResult.guess.search("点") != -1) {
                            if (parseInt(allResult.guess.split("点")[0].split("豹子")[1]) == value / 3 && resultdxds.baozi == 1) {
                                if (false) {
                                    allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = ${1.7 * allResult.amount}
                                    where id = ${allResult.id};
                                    update users
                                    set balance      = balance + ${parseInt(1.7 * allResult.amount - allResult.amount)},
                                        todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount)},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount},
                                        lastbet_time = now()
                                    where telegramid = "${allResult.telegramid}";`
                                } else {
                                    allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                    winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                    allResultSql = `${allResultSql}
                                    update pc_bet
                                    set result = ${allResult.peilv * allResult.amount}
                                    where id = ${allResult.id};
                                    update users
                                    set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                        todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                        liushui      = liushui + ${allResult.amount},
                                        zongliushui  = zongliushui + ${allResult.amount},
                                        lastbet_time = now()
                                    where telegramid = "${allResult.telegramid}";`
                                }

                            } else {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}
                                update pc_bet
                                set result = 0
                                where id = ${allResult.id};
                                update users
                                set lastbet_time = now(),
                                    todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                    liushui      = liushui + ${allResult.amount},
                                    zongliushui  = zongliushui + ${allResult.amount}
                                where telegramid = "${allResult.telegramid}";`
                            }
                        }
    */
                        /*
                                                if (allResult.guess == "龙" || allResult.guess == "虎" || allResult.guess == "合") {
                                                    if (longhu == allResult.guess) {
                                                        if (resultdxds.shunzi == 1 || value == 10 || value == 11) {
                                                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                                            allResultSql = `${allResultSql}
                                                            update pc_bet
                                                            set result = ${1.7 * allResult.amount}
                                                            where id = ${allResult.id};
                                                            update users
                                                            set balance      = balance + ${parseInt(1.7 * allResult.amount)},
                                                                todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                                                liushui      = liushui + ${allResult.amount},
                                                                zongliushui  = zongliushui + ${allResult.amount},
                                                                lastbet_time = now()
                                                            where telegramid = "${allResult.telegramid}";`
                                                        } else if (allResult.guess == "龙" || allResult.guess == "虎") {
                                                            allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                                            winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                                            allResultSql = `${allResultSql}
                                                            update pc_bet
                                                            set result = ${allResult.peilv * allResult.amount}
                                                            where id = ${allResult.id};
                                                            update users
                                                            set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                                                todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                                                liushui      = liushui + ${allResult.amount},
                                                                zongliushui  = zongliushui + ${allResult.amount},
                                                                lastbet_time = now()
                                                            where telegramid = "${allResult.telegramid}";`
                                                        }
                                                    } else {
                                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                                        allResultSql = `${allResultSql}
                                                        update pc_bet
                                                        set result = 0
                                                        where id = ${allResult.id};
                                                        update users
                                                        set lastbet_time = now(),
                                                            todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                                            liushui      = liushui + ${allResult.amount},
                                                            zongliushui  = zongliushui + ${allResult.amount}
                                                        where telegramid = "${allResult.telegramid}";`
                                                    }
                                                }

                                                if (allResult.guess == "合") {
                                                    if (longhu == allResult.guess) {
                                                        if (false) {
                                                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7 * allResult.amount)}</b>\n`
                                                            allResultSql = `${allResultSql}
                                                            update pc_bet
                                                            set result = ${1.7 * allResult.amount}
                                                            where id = ${allResult.id};
                                                            update users
                                                            set balance      = balance + ${parseInt(1.7 * allResult.amount)},
                                                                todayhuishui = todayhuishui - ${parseInt(1.7 * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                                                liushui      = liushui + ${allResult.amount},
                                                                zongliushui  = zongliushui + ${allResult.amount},
                                                                lastbet_time = now()
                                                            where telegramid = "${allResult.telegramid}";`
                                                        } else {
                                                            allResultMessage = `${allResultMessage}<code>${allResult.name}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                                            winResultMessage = `${winResultMessage}<code>${allResult.firstname}</code> ${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv * allResult.amount)}</b>\n`
                                                            allResultSql = `${allResultSql}
                                                            update pc_bet
                                                            set result = ${allResult.peilv * allResult.amount}
                                                            where id = ${allResult.id};
                                                            update users
                                                            set balance      = balance + ${parseInt(allResult.peilv * allResult.amount)},
                                                                todayhuishui = todayhuishui - ${parseInt(allResult.peilv * allResult.amount - allResult.amount + conf.allreturnwater * allResult.amount)},
                                                                liushui      = liushui + ${allResult.amount},
                                                                zongliushui  = zongliushui + ${allResult.amount},
                                                                lastbet_time = now()
                                                            where telegramid = "${allResult.telegramid}";`
                                                        }
                                                    } else {
                                                        allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                                                        allResultSql = `${allResultSql}
                                                        update pc_bet
                                                        set result = 0
                                                        where id = ${allResult.id};
                                                        update users
                                                        set lastbet_time = now(),
                                                            todayhuishui = todayhuishui + ${allResult.amount - conf.allreturnwater * allResult.amount},
                                                            liushui      = liushui + ${allResult.amount},
                                                            zongliushui  = zongliushui + ${allResult.amount}
                                                        where telegramid = "${allResult.telegramid}";`
                                                    }
                                                }
                        */
                        // 13 14也可以回本
                        /*                        if (value == 13 || value == 14) {
                                                    allResultSql = `${allResultSql}
                                                        update pc_bet
                                                        set result = 0
                                                        where id = ${allResult.id};
                                                        update users
                                                        set balance = balance + ${allResult.amount}
                                                        where telegramid = "${allResult.telegramid}";`
                                                }*/
                    }
                    conf.pool.getConnection(function (err, connection) {
                        if (err) {
                            bot.sendMessage(conf.chatid, `${resultid}期接口不稳定，此期投注仍有效，联系客服处理`, {
                                reply_markup: JSON.stringify({
                                    inline_keyboard: conf.inline_keyboard
                                })
                            });
                            console.log(err);
                            return;
                        }
                        ;

                        connection.query(`
                    ${allResultSql}
                    ${invitesql}`, (error, result) => {
                            console.log('allResultSql====', allResultSql)
                            console.log(error)
                            if (error) {
                                bot.sendMessage(conf.chatid, `${resultid}期接口不稳定，此期投注仍有效，联系客服处理`, {
                                    reply_markup: JSON.stringify({
                                        inline_keyboard: conf.inline_keyboard
                                    })
                                });
                                console.log(error);
                                return;
                            }
                            connection.query(`SELECT *
                                              FROM pc_result
                                              WHERE type = '${conf.type}'
                                              order by result_time desc LIMIT 20;
                            select *
                            from users
                            where resultid = "${resultid}";`, (error, result) => {
                                console.log(error)
                                if (error) return error;
                                // connection.destroy()
                                if (allResultMessage.length > 600) {
                                    allResultMessage = allResultMessage.substring(0, 600);
                                    allResultMessage += `...等${resultArray.length}次投注\n`
                                }
                                var quanbutouzhu = ""
                                for (let index = 0; index < resultArray.length; index++) {
                                    quanbutouzhu += `${resultArray[index].guess}-${resultArray[index].amount}元 赔率：${resultArray[index].peilv}倍\n`;
                                }

                                let history = ''
                                // 历史开奖
                                connection.query(`SELECT *
                                                  FROM pc_result
                                                  WHERE type = '${conf.type}'
                                                    and one is not null
                                                    and two is not null
                                                    and three is not null
                                                  ORDER BY id DESC LIMIT 10;`, (error, result) => {
                                    console.log(error)
                                    if (error) return error;
                                    if (result) {
                                        result.forEach(item => {
                                            history += `${item.id}期 <code>${item.one} ${item.two} ${item.three} = ${item.one + item.two + item.three} ${item.big == 1 ? "大" : ""}${item.small == 1 ? "小" : ""} ${item.odd == 1 ? "单" : ""} ${item.even == 1 ? "双" : ""} ${item.baozi == 1 ? " 豹子" : ""} ${item.shunzi == 1 ? " 顺子" : ""} ${item.duizi == 1 ? " 对子" : ""} ${item.jida == 1 ? " 极大" : ""} ${item.jixiao == 1 ? " 极小" : ""}</code>  \n`
                                        });
                                    }

                                    var sendruselttxt = `<code>${resultid}期</code>开奖结果\n${a}+${b}+${c}=${a + b + c}  结果-${daxiao}-${danshuang}-${(baozi == "" ? baozi : " " + baozi + " ")}${(shunzi == "" ? shunzi : " " + shunzi)}${(duizi == "" ? duizi : " " + duizi)}-${jizhi}\n\n恒旺集团娱乐🐲\n每日充值送10%彩金/负盈利反水%5\n充值地址:\nTWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd \n ———————————————————— \n 🧧㊗️老板们多多盈利，美金越来越多💵💵💵🧧\n🎉手气爆棚 天天提款🧨🧨🧨\n🎉财源广进  天天嫩模 🧨🧨🧨\n\n👍 公平 公正 公开 \n👍💎月入百万不是梦💎\n💎看你心动不行动💎 \n \n <code>------历史开奖走势------</code> \n ${history}`;

                                    bot.sendMessage(conf.chatid, sendruselttxt, {
                                        parse_mode: "HTML",
                                        disable_web_page_preview: true,
                                        reply_markup: JSON.stringify({
                                            inline_keyboard: conf.guize_inline_keyboard
                                        })
                                    })

                                    bot.sendPhoto(chatid, kjjg, {
                                        parse_mode: 'HTML',
                                        disable_web_page_preview: true,
                                        caption: winResultMessage
                                    })
                                    connection.destroy()
                                })


                                /*setTimeout(function () {

                                    bot.sendMessage(conf.chatid, `结果已录入，点数：${a}+${b}+${c}=${a + b + c} ${longhu}\n您的全部投注如下：\n${quanbutouzhu}`, {
                                        reply_to_message_id: msg.message_id
                                    })
                                        .then(res => {

                                        })
                                }, 1000)*/
                            });
                        });
                    });
                });
            }
        });
    });
}

function utf16toEntities(str) {
    const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, (char) => {
        let H;
        let L;
        let code;
        let s;

        if (char.length === 2) {
            H = char.charCodeAt(0); // 取出高位
            L = char.charCodeAt(1); // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
            s = `&#${code};`;
        } else {
            s = char;
        }

        return s;
    });

    return str;
}

function entitiestoUtf16(strObj) {
    const patt = /&#\d+;/g;
    const arr = strObj.match(patt) || [];

    let H;
    let L;
    let code;

    for (let i = 0; i < arr.length; i += 1) {
        code = arr[i];
        code = code.replace('&#', '').replace(';', '');
        // 高位
        H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
        // 低位
        L = ((code - 0x10000) % 0x400) + 0xDC00;
        code = `&#${code};`;
        const s = String.fromCharCode(H, L);
        strObj = strObj.replace(code, s);
    }
    return strObj;
}


function paiming(chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT nickname,
                                 todayhuishui,
                                 jndtodayhuishui,
                                 (todayhuishui + jndtodayhuishui + pctodayhuishui) AS sum
                          FROM users
                          where (todayhuishui + jndtodayhuishui + pctodayhuishui) < 0
                          ORDER BY sum asc limit 5;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var paiminglist = "";
            for (let index = 0; index < result.length; index++) {
                if (index == 0) {
                    paiminglist += `🥇 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
                } else if (index == 1) {
                    paiminglist += `🥈 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
                } else if (index == 2) {
                    paiminglist += `🥉 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
                } else {
                    paiminglist += `🎖 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
                }
            }
            bot.sendPhoto(chatid, './img/phb.jpg', {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                reply_markup: {
                    inline_keyboard: conf.yjc_inline_keyboard
                },
                caption: `🔥🔥今日总战报  🔥🔥\n\n当月玩家总下分100wU\n当月玩家盈利金额50wU\n🏆今日截止目前盈利玩家排行榜前五名🏆\n\n${paiminglist}\n🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨\n恭喜以上截至目前最高盈利的老板，\n祝各老板们日进斗金，腰缠万贯，八方来财，荷包满满\n欢迎各位老板踊跃提款，\n为各位老板提供最好的服务\n🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨`
            })
                .then(res => {
                    if (res.chat.id == conf.chatid) {
                        bot.pinChatMessage(res.chat.id, res.message_id)
                    }
                })
        });
    })
}


function getlastday(lastday) {
    return moment(Math.round(new Date) - lastday * 60 * 60 * 24 * 1000).format("YYYY-MM-DD 00:%")
}

app.get('/table/pay/go', (req, res) => {

    conf.pool.getConnection(function (err, connection) {
        var params = JSON.parse(req.query.data);
        if (err) {
            common.reqError(res);
        } else if (common.oc(req)) {
            connection.query(`select *
                              from pay
                              where id = ${params.id};`, (error, result) => {
                if (error) {
                    common.reqError(res);
                } else {
                    if (!result[0]) {
                        res.send({
                            code: 400,
                            msg: "该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state != 0) {
                        res.send({
                            code: 400,
                            msg: "该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update pay
                                          set state      = 1,
                                              changetime = now()
                                          where id = ${params.id};
                        update users
                        set balance = balance + ${params.amount}
                        where telegramid = ${params.telegramid};`, (error, result) => {
                            if (error) {
                                common.reqError(res);
                            } else {
                                connection.query(`select *
                                                  from pay
                                                  where id = ${params.id};
                                SELECT *
                                FROM users
                                where telegramid = "${params.telegramid}";`, (error, result) => {
                                    connection.destroy();
                                    if (error) {
                                        common.reqError(res);
                                    } else {
                                        res.send({
                                            code: 200,
                                            msg: result[0]
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `您的上分申请已通过，当前余额${result[1][0].balance}，祝您游戏愉快`, {
                                                reply_to_message_id: result[0][0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            common.reqError(res);
        }
    });
})


app.get('/table/pay/refuse', (req, res) => {
    conf.pool.getConnection(function (err, connection) {
        var params = JSON.parse(req.query.data);
        if (err) {
            common.reqError(res);
        } else if (common.oc(req)) {
            connection.query(`select *
                              from pay
                              where id = ${params.id};`, (error, result) => {
                if (error) {
                    common.reqError(res);
                } else {
                    if (!result[0]) {
                        res.send({
                            code: 400,
                            msg: "该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state != 0) {
                        res.send({
                            code: 400,
                            msg: "该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update pay
                                          set state      = -1,
                                              changetime = now()
                                          where id = ${params.id};`, (error, result) => {
                            if (error) {
                                common.reqError(res);
                            } else {
                                connection.query(`select *
                                                  from pay
                                                  where id = ${params.id};`, (error, result) => {
                                    connection.destroy();
                                    if (error) {
                                        common.reqError(res);
                                    } else {
                                        res.send({
                                            code: 200,
                                            msg: result
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `上分失败，金额：${params.amount}`, {
                                                reply_to_message_id: result[0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            common.reqError(res);
        }
    });
})

app.get('/table/withdrawal/go', (req, res) => {
    conf.pool.getConnection(function (err, connection) {
        var params = JSON.parse(req.query.data);
        if (err) {
            common.reqError(res);
        } else if (common.oc(req)) {
            connection.query(`select *
                              from withdrawal
                              where id = ${params.id};`, (error, result) => {
                if (error) {
                    common.reqError(res);
                } else {
                    if (!result[0]) {
                        res.send({
                            code: 400,
                            msg: "该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state != 0) {
                        res.send({
                            code: 400,
                            msg: "该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update withdrawal
                                          set state      = 1,
                                              changetime = now()
                                          where id = ${params.id};`, (error, result) => {
                            if (error) {
                                common.reqError(res);
                            } else {
                                connection.query(`select *
                                                  from withdrawal
                                                  where id = ${params.id};
                                SELECT *
                                FROM users
                                where telegramid = "${params.telegramid}";`, (error, result) => {
                                    connection.destroy();
                                    if (error) {
                                        common.reqError(res);
                                    } else {
                                        res.send({
                                            code: 200,
                                            msg: result[0]
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `您的下分申请已通过,当前余额${result[1][0].balance},欢迎再次光临`, {
                                                reply_to_message_id: result[0][0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            common.reqError(res);
        }
    });
})

app.get('/table/withdrawal/refuse', (req, res) => {
    conf.pool.getConnection(function (err, connection) {
        var params = JSON.parse(req.query.data);
        if (err) {
            common.reqError(res);
        } else if (common.oc(req)) {
            connection.query(`select *
                              from withdrawal
                              where id = ${params.id};`, (error, result) => {
                if (error) {
                    common.reqError(res);
                } else {
                    if (!result[0]) {
                        res.send({
                            code: 400,
                            msg: "该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state != 0) {
                        res.send({
                            code: 400,
                            msg: "该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update withdrawal
                                          set state      = -1,
                                              changetime = now()
                                          where id = ${params.id};
                        update users
                        set balance = balance + ${params.amount}
                        where telegramid = ${params.telegramid};`, (error, result) => {
                            if (error) {
                                common.reqError(res);
                            } else {
                                connection.query(`select *
                                                  from withdrawal
                                                  where id = ${params.id};`, (error, result) => {
                                    connection.destroy();
                                    if (error) {
                                        common.reqError(res);
                                    } else {
                                        res.send({
                                            code: 200,
                                            msg: result
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `下分失败，金额：${params.amount}`, {
                                                reply_to_message_id: result[0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            common.reqError(res);
        }
    });
})


function listenUSDTOrder() {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pay
                          where applytimestamp <= unix_timestamp() - 600
                            and state = 0;
        update pay
        set state = -1
        where applytimestamp <= unix_timestamp() - 600
          and state = 0;`, (error, result) => {
            connection.destroy();
            if (error) return error;
            for (let index = 0; index < result[0].length; index++) {
                bot.sendMessage(result[0][index].telegramid, `此订单已过期，请重新获取订单`, {
                    parse_mode: 'HTML',
                    reply_to_message_id: result[0][index].replyMessageid
                })
            }
        });
    })
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM pay
                          where applytimestamp > unix_timestamp() - 600
                            and state = 0;
        SELECT *
        FROM pay
        where applytimestamp >= unix_timestamp() - 600
          and state = 1;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var resultsuccess = []
            for (let index = 0; index < result[1].length; index++) {
                resultsuccess.push(result[1][index].transaction_id)
            }
            var sql = "";
            for (let index = 0; index < result[0].length; index++) {

                request(apitrc)
                    .then((body) => {
                        for (let i = 0; i < JSON.parse(body).data.length; i++) {
                            if (JSON.parse(body).data[i].type == "Transfer" && JSON.parse(body).data[i].to == conf.czaddress && (JSON.parse(body).data[i].value) / 1000000 == result[0][index].amount && (JSON.parse(body).data[i].block_timestamp) / 1000 + 600 > parseInt(result[0][index].applytimestamp)) {
                                var issame = false;
                                for (let a = 0; a < resultsuccess.length; a++) {
                                    if (resultsuccess[a] == JSON.parse(body).data[i].transaction_id) {
                                        issame = true
                                    }

                                }
                                if (!issame) {
                                    sql = sql + `update pay
                                                 set state          = 1,
                                                     transaction_id = "${JSON.parse(body).data[i].transaction_id}"
                                                 where applytimestamp = '${result[0][index].applytimestamp}';
                                    update users
                                    set balance = balance + ${(result[0][index].amount * 6.75).toFixed(2)}
                                    where telegramid = '${result[0][index].telegramid}';`;
                                    bot.editMessageText(`<b>充值成功，金额： ${result[0][index].amount} USDT = ${(result[0][index].amount * 6.75).toFixed(2)} RMB</b>`, {
                                        parse_mode: 'HTML',
                                        message_id: result[0][index].replyMessageid,
                                        chat_id: result[0][index].telegramid
                                    })
                                    if (conf.isnoticegroup) {
                                        bot.sendMessage(conf.sxfgroupid, `用户：${result[0][index].name}\nID：${result[0][index].telegramid}\n使用机器人上分成功！\n上分金额：${(result[0][index].amount).toFixed(2)}USDT = ${(result[0][index].amount * 6.75).toFixed(2)} RMB\n祝您一路长虹！`, {
                                            parse_mode: 'HTML',
                                        })
                                    }
                                }
                            }
                            if (index == result[0].length - 1 && sql != "" && i == JSON.parse(body).data.length - 1) {
                                conf.pool.getConnection(function (err, connection) {
                                    if (err) return err;
                                    connection.query(`${sql}`, (error, res) => {
                                        connection.destroy();
                                        if (error) return error;
                                    });
                                })
                            } else if (index == result[0].length - 1 && sql == "" && i == JSON.parse(body).data.length - 1) {

                            }
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    })
            }
        });
    })
}

function qxorder(callbackQuery) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`update pay
                          set state = -1
                          where replyMessageid = "${callbackQuery.message.message_id}";`, (error, result) => {
            connection.destroy();
            if (error) {
                console.log(error);
                return
            }
            ;
            bot.editMessageText(`🔁<b>您的充值订单已成功取消</b>`, {
                chat_id: callbackQuery.from.id,
                message_id: callbackQuery.message.message_id,
                parse_mode: "HTML"
            }).catch(err => {
                console.log(err);
            });
        });
    })
}

async function transferUSDT(trx_address, amount) {
    const {
        abi
    } = await tronWeb.trx.getContract(contractaddress_usdt);

    const contract = tronWeb.contract(abi.entrys, contractaddress_usdt);
    hashid = await contract.methods.transfer(trx_address, amount * 1000000).send();
    console.log(hashid);


}


function yongjinpaiming(chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where zongyongjin > 0
                          ORDER BY zongyongjin desc limit 10;
        select *
        from yongjinchi
        where id = 1;`, (error, result) => {
            if (error) return error;
            connection.destroy();
            var paiminglist = "";
            for (let index = 0; index < result[0].length; index++) {
                if (index == 0) {
                    paiminglist += `🥇 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.37).toFixed(2)}</code>\n\n`
                } else if (index == 1) {
                    paiminglist += `🥈 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.25).toFixed(2)}</code>\n\n`
                } else if (index == 2) {
                    paiminglist += `🥉 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.15).toFixed(2)}</code>\n\n`
                } else if (index == 3) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.10).toFixed(2)}</code>\n\n`
                } else if (index == 4) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.05).toFixed(2)}</code>\n\n`
                } else if (index == 5) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.03).toFixed(2)}</code>\n\n`
                } else if (index == 6) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.02).toFixed(2)}</code>\n\n`
                } else if (index == 7) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                } else if (index == 8) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                } else if (index == 9) {
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                }
            }
            bot.sendPhoto(chatid, './img/yjc.jpg', {
                parse_mode: 'HTML',
                disable_web_page_preview: true,
                caption: `<b>🧧🧧🧧佣金排行榜🧧🧧🧧</b>\n\n（按照下级充值金额排名）\n\n本周待分红奖池 <code>${result[1][0].amount}</code> 元\n\n${paiminglist}\n\n\n最低每星期佣金分红3000rmb\n推出佣金池活动 从推广链接进来的用户永久返利上级1%   并且充值的百分之5拿来投入佣金池中 \n推广的客户充值和投注是永久有效的\n每周日只清理佣金池分红‼️\n进入  @shouyaokuaisanbot\n发送/start  点击代理中心生成群链接\n佣金池排行榜也可查看\n每星期天晚上00.00分红发放佣金   佣金可直接提现\n🔥恒旺佣金排行榜🔥🎉🎉🎉\n\n发现用小号刷佣金的，一律无效清除\n禁止违规操作❗️❗️❗️❗️❗️❗️`,
                reply_markup: {
                    inline_keyboard: conf.yjc_inline_keyboard
                }
            })
                .then(res => {
                    bot.pinChatMessage(res.chat.id, res.message_id)
                })
        });
    })
}


function yongjinpaiminguser(chatid) {
    conf.pool.getConnection(function (err, connection) {
        if (err) return err;
        connection.query(`SELECT *
                          FROM users
                          where zongyongjin > 0
                          ORDER BY zongyongjin desc limit 10;
        select *
        from yongjinchi
        where id = 1;
        select *
        from users
        where telegramid = "${chatid}";`, (error, result) => {
            if (error) return error;
            connection.query(`SELECT count(*)
                              FROM users
                              where zongyongjin > ${result[2][0].zongyongjin};`, (error, res) => {
                if (error) return error;
                connection.destroy();
                var paiminglist = "";
                var isqianshi = false
                var yujifenhong = 0
                for (let index = 0; index < result[0].length; index++) {
                    if (result[0][index].telegramid == chatid) {
                        isqianshi = true
                        if (index == 0) {
                            yujifenhong = result[1][0].amount * 0.37
                        } else if (index == 1) {
                            yujifenhong = result[1][0].amount * 0.25
                        } else if (index == 2) {
                            yujifenhong = result[1][0].amount * 0.15
                        } else if (index == 3) {
                            yujifenhong = result[1][0].amount * 0.10
                        } else if (index == 4) {
                            yujifenhong = result[1][0].amount * 0.05
                        } else if (index == 5) {
                            yujifenhong = result[1][0].amount * 0.03
                        } else if (index == 6) {
                            yujifenhong = result[1][0].amount * 0.02
                        } else if (index == 7) {
                            yujifenhong = result[1][0].amount * 0.01
                        } else if (index == 8) {
                            yujifenhong = result[1][0].amount * 0.01
                        } else if (index == 9) {
                            yujifenhong = result[1][0].amount * 0.01
                        }
                    }
                    if (index == 0) {
                        paiminglist += `🥇 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.37).toFixed(2)}</code>\n\n`
                    } else if (index == 1) {
                        paiminglist += `🥈 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.25).toFixed(2)}</code>\n\n`
                    } else if (index == 2) {
                        paiminglist += `🥉 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.15).toFixed(2)}</code>\n\n`
                    } else if (index == 3) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.10).toFixed(2)}</code>\n\n`
                    } else if (index == 4) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.05).toFixed(2)}</code>\n\n`
                    } else if (index == 5) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.03).toFixed(2)}</code>\n\n`
                    } else if (index == 6) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.02).toFixed(2)}</code>\n\n`
                    } else if (index == 7) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                    } else if (index == 8) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                    } else if (index == 9) {
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount * 0.01).toFixed(2)}</code>\n\n`
                    }
                }
                bot.sendPhoto(chatid, './img/yjc.jpg', {
                    parse_mode: 'HTML',
                    disable_web_page_preview: true,
                    caption: `<b>🧧🧧🧧佣金排行榜🧧🧧🧧</b>\n\n（按照下级充值金额排名）\n\n本周待分红奖池 <code>${result[1][0].amount}</code> 元\n\n${paiminglist}\n\n我的排名 <code>${res[0]['count(*)'] + 1}</code>，预计分红 <code>${yujifenhong}</code> 元\n\n发现用小号刷佣金的，一律无效清除\n禁止违规操作❗️❗️❗️❗️❗️❗️`
                })
            });
        });
    })
}
